html部分
<div class="wrap">
<ul>
<li style="background:rgb(241, 136, 136)">
第一图</li>
<li style="background:rgb(71, 216, 148)">第二图</li>
<li style="background:rgb(106, 69, 240)">第三图</li>
<li style="background:rgb(240, 69, 149)">第四图</li>
<li style="background:rgb(235, 122, 16)">第五图</li>
<li style="background:rgb(241, 136, 136)">
第一图</li>
</ul>
</div>
css部分
*{
padding: 0;
margin: 0;
}
.wrap{
width: 100%;
height: 400px;
position: relative;
overflow: hidden;
}
.wrap ul li{
text-align: center;
line-height: 400px;
font-size: 50px;
width: 100%;
height:400px;
}
.wrap ul{
animation: moves1 10s linear infinite;
}
js部分
let sheet = document.styleSheets[0]; //获取所有样式
let len = document.querySelectorAll('.wrap ul li');
//设置样式
sheet.insertRule("@keyframes moves1{from{ margin-top:0; }to{ margin-top:"+-len[0].clientHeight*(len.length-1)+"px}}",sheet.rules.length); //在样式表最后添加
原理:
利用css3@keyframes属性设置动画滚动效果,把第一帧添加一个放于最后,用于循环一次切换衔接, 如果项目中的li个数和高度都为固定则不需要写js去设置动态数值,直接在css中写死就好
insertRule(rule,index)
rule :要添加到样式表的规则。
index:要把规则插入或附加到 cssRules 数组中的位置。