先上效果
具体实现代码(如果用到vue项目中的css要取消scoped否则不生效)
在这里插入代码片< ! 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 % {
}
}
. 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> ` ` `