1、html部分

<div class="xsck-list">
 <div :key="item.id" class="xsck-list__li" v-for="(item, index) in orderList">
    <div class="xsck-list__left">
        {{item.biOrgsName}}
    </div>
    <div class="xsck-list__right">
       {{item.taxAllAmount}}
    </div>
  </div>
 </div>

2、js部分

scroll.js

// 动态设置keyframes实现向上滚动
// keyName动画名称,el执行动画的元素, time动画执行时间,isInitStyle是否第一次设置
const setKeyframes = (keyName, el, time = 1000, isInitStyle) => {
    // 为实现动画无缝播放,列表元素的值应是[1,2,3,1,2,3]这样的形式,这样才能让123循环无缝播放
    // 因为元素列表需要重复一份,所以移动的高度是元素高度的一半
    const transformHeight = el.offsetHeight / 2;
    const keyframes = `@keyframes ${keyName}{
      0% {
        transform: translateY(0) translateZ(0);
        z-index: 1;
      }
      100% {
        transform: translateY(-${transformHeight}px) translateZ(0);
        z-index: 1;
      }
    }`;
    if (!isInitStyle) {
        const style = document.createElement('style');
        style.type = 'text/css';
        style.innerHTML = keyframes;
        document.getElementsByTagName('head')[0].appendChild(style);
        } else {
        const keyframeItem = getkeyframes(keyName);
        const index = keyframeItem.index;
        // deleteRule方法用来从当前样式表对象中删除指定的样式规则
        keyframeItem.styleSheet.deleteRule(index);
        keyframeItem.styleSheet.insertRule(keyframes, index);
   }

  // 为需要设置滚动动画的元素设置动画值
   el.setAttribute(
     'style',
    // animation-fill-mode: forwards 将动画重置为第一帧,实现无缝的播放了
    `animation:${keyName} ${time}s linear infinite;animation-fill-mode: forwards`,
    );
};
// 获取keyframes
const getkeyframes = (name) => {
  const animation = {};
  // 获取所有的style
  const ss = document.styleSheets;
  for (let i = 0; i < ss.length; i += 1) {
    const item = ss[i];
    try {
      if (
        item.cssRules &&
        item.cssRules[0] &&
        item.cssRules[0].name &&
        item.cssRules[0].name === name
      ) {
        animation.cssRule = item.cssRules[0];
        animation.styleSheet = ss[i];
        animation.index = 0;
      }
    } catch (e) {
      console.warn(`Can't read the css rules of: ${item.media}`, e);
    }
  }
  return animation;
};

export default {
  setKeyframes,
  getkeyframes,
};

3、调用

import scrollObj from '../../util/scroll';

// 为实现动画无缝播放,列表元素的值应是[1,2,3,1,2,3]这样的形式,这样才能让123循环无缝播放
this.orderList = data.concat(data);
if (this.orderList.length <= 0) {
    return;
}
setTimeout(() => {
    const el = document.querySelector('.xsck-list');
    const domOffsetHeight = el.offsetHeight;
    // 15s走1000像素高度的来算该动画的时间
    const time = (15 / 1000) * domOffsetHeight;
    scrollObj.setKeyframes('myNove', el, time, this.initStyle);
    this.initStyle = true;
}, 10);

4、其他

transform: translateZ(0) 可解决抖动的问题;
z-index: 1可解决字体模糊的问题;

5、参考
(1) https://www.jianshu.com/p/b7b...
(2) https://blog.csdn.net/qq_4180...
(3) https://developer.mozilla.org...
(4) https://developer.mozilla.org...


悠悠风来
153 声望13 粉丝

你不拼一把,怎么知道自己是不是金子