先上效果
具体实现代码(如果用到vue项目中的css要取消scoped否则不生效)
javascript
在这里插入代码片<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>星空</title>
<style lang="scss">
.table-container {
height: 300px;
overflow: auto;
border: 1px solid #08e6e4;
text-align: center;
line-height: 108px;
}
.on {
width: 100px;
height: 100px;
background-color: #08e6e4;
}
.off {
width: 100px;
height: 100px;
background-color: #f21;
}
@keyframes scrollTable {
0% {
transform: translateY(0);
}
100% {
/* transform: translateY(-2000%); */
}
}
.clickad {
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
<div class="table-container" ref="tableContainer">
<div v-for="number in 20" :key="number" class="table-item"
:class="{ on: number % 2 == 0, off: number % 2 != 0 }">
<div class="names"> {{number}} </div>
</div>
</div>
<button class="clickad" @click="clickad">点击滚动</button>
</div>
</div>
<!-- cdn引入vue -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.2/vue.js"></script>
<script>
// 初始化
new Vue({
el: "#app",
data() {
return {
};
},
methods: {
// 动态计算方法
startAnimation() {
const container = document.querySelector('.table-container');
const tableItems = document.querySelectorAll('.table-container .table-item');
const containerHeight = container.offsetHeight; // 获取容器的高度
let tableHeight = 0;
tableItems.forEach((item) => {
console.log(item);
tableHeight += item.scrollHeight; // 累加每个表格项的高度
});
if (containerHeight < tableHeight) {
const translateYDistance = -(tableHeight - containerHeight); // 计算需要移动的高度
tableItems.forEach((item) => {
item.style.transform = `translateY(${translateYDistance}px)`; // 设置初始位置
console.log(item.style.transform);
});
const animationDuration = (tableHeight / containerHeight) * 2; // 根据内容高度和容器高度计算动画持续时间
tableItems.forEach((item) => {
item.style.animation = `scrollTable ${animationDuration}s infinite linear`; // 设置动画
console.log(item.style.animation);
});
}
},
// 点击事件
clickad() {
this.startAnimation()
},
},
});
</script>
</body>
</html>```