场景:横向平滑滚动展示消息;消息列表是接口获取;类似于游戏中的广播消息
方法一、纯css animation
在css中定义关键帧,并写入animation样式
// animation: line 20s linear infinite; // @keyframes line{ // 0%{ // transform: translateX(0); // } // 100%{ // transform: translateX(-100%); // } // }
产生问题:只能写死动画时间,若接口返回数据比较大,滚动动画就会很快,效果不理想;
方法二、js+css animation
js获取接口返回数据生成的dom元素宽度,根据宽度来定义时间与速度
const width = this.$refs.subBox.offsetWidth const time = Math.ceil(width/80) this.$refs.subBox.style.animation = `line ${time}s linear infinite`;
css关键帧动画名定义不变:
// @keyframes line{ // 0%{ // transform: translateX(0); // } // 100%{ // transform: translateX(-100%); // } // }
产生问题:vue项目由于scoped,打包文件对应的样式格式 data-v-xxxxx,无法与js定义的动画animationName 关键帧对应上;
换个思路,结合方法一,如果先在css中定义动画名称animationName,通过js获取接口返回数据生成的dom元素宽度,再通过js修改动画时间animationDuration同样无法生效;
解决办法:全局定义关键帧
全局css文件中定义关键帧动画名,js获取接口返回数据生成DOM元素宽度,然后js添加动画样式,定义动画时长,达到效果;
方法三、当前页面js定义关键帧,插入css styleSheets,再定义animation
const width = this.$refs.subBox.offsetWidth const time = Math.ceil(width/80) const keyframesLine = ` @keyframes line{ 0%{ transform: translateX(0); } ${120/time}%{ transform: translateX(0); } 100%{ transform: translateX(-100%); } } ` var style =document.styleSheets[0] style.insertRule(keyframesLine,style.length-1) this.$refs.subBox.style.animation = `line ${time}s linear infinite`;
达到效果,根据接口实际数据,定义动画时长
补充说明
设置动画延迟,只会在第一次生效,若要每次循环都有延时,改变思路,在每一次动画过程中,开始一段进度不发生变化即可
@keyframes line{ 0%{ transform: translateX(0); } ${120/time}%{ transform: translateX(0); } 100%{ transform: translateX(-100%); } }
当中,在某一进度无变化
${120/time}%{
transform: translateX(0);
}