天天看點

js實作清單垂直無限滾動

先上核心js

(function ($) {
  $.fn.myScroll = function (options) {
    //預設配置
    let defaults = {
      speed: 40, //滾動速度,值越大速度越慢
      // rowHeight: 38, //每行的高度
      line: 6,
    };
    let opts = $.extend({}, defaults, options),
      intId = null;
    function marquee(obj) {
      let rowHeight=obj.find("ul:first").height()/opts["line"]
      obj.find("ul").animate({
        marginTop: '-=1'
      }, 0, function () {
        let s = Math.abs(parseInt($(this).css("margin-top")));
        if (s >= rowHeight) {
          $(this).find("li").slice(0, 1).appendTo($(this));
          $(this).css("margin-top", 0);
        }
      });
    }
    this.each(function (i) {
      let speed = opts["speed"],
        _this = $(this);
      intId = setInterval(function () {
        marquee(_this);
      }, speed);
      _this.hover(function () {
        clearInterval(intId);
      }, function () {
        intId = setInterval(function () {
          marquee(_this);
        }, speed);
      });

    });
    return intId
  }
  $.fn.closeScroll=function(intId){
    clearInterval(intId);
    $(this).unbind();
  }
})(jQuery);
           

把js引入項目後使用過程如下:

html部分結構必須為ul+li形式

<div class="ratio-top__box">
  <div v-if="accessTopList.length==0">暫無資料...</div>
  <ul>
    <li v-for="(item,index) in accessTopList" :key="index">
      <span :title="item.label">{{item.label}}</span>
      <span>{{item.count}}</span>
    </li>
  </ul>
</div>
           

此步為監聽資料長度是否要進行滾動判斷,如果無這樣的需求可以直接在mounted中初始化

watch: {
 accessTopList(newVal, oldVal) {
    if (newVal.length != oldVal.length) {
      this.scroll('ratio-top__box', 5, newVal)
    }
  },
},
methods:{
  // html中對應的className,顯示行數,全部清單val
  scroll(className, line, val) {
    if (val.length > line) {
      $('.' + className).closeScroll(this['_' + className])
      setTimeout(function () {
        this['_' + className] = $('.' + className).myScroll({
          speed: 25,
          line: line,
        })
      }, 5000)
    } else {
      $('.' + className).closeScroll(this['_' + className])
    }
  },
}
           

css部分要注意,在父容器一定要設定溢出隐藏,ul一定要設定高度

.pillar-box {
  height: rem(242);
   overflow: hidden;

   ul {
     height: rem(234);
   }
 }