JS 无间隙滚动 封装

新建一个 页面魔板 : 引入 JS 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>无间隙滚动</title>
</head>
<style>
    ul{
      list-style: none;
    }
    *{
      padding: 0;
      margin: 0;
    }
    #box1{
      width: 300px;
      height: 100px;
      border: 1px solid #ccc;
    }
    #box2{
      width: 100px;
      height: 300px;
      border: 1px soild #cccccc;
    }

    ul li{
      float: left;
      width: 100px;
      height: 100px;
    }
</style>
<body>

  <div id="box1">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>
  </div>

  <br/>
  <hr/>

  <div id="box2">
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
      <li>5</li>
    </ul>
  </div>

</body>
<script src="scoller.js"></script>
</html>

scoller.js 文件

function Scroll(options){
  this.el = document.getElementById(options.el);
  this.ul = this.el.getElementsByTagName("ul")[0];
  this.li = this.ul.getElementsByTagName("li");
  this.direction = options.direction;
  this.speed = options.speed;
  this.index = 0;
  this.init();
}


Scroll.prototype = {
  init:function(){
    // 效果的开始
    this.li_num = this.li.length;
    this.el.style.overflow = 'hidden';
    if(this.direction == "x"){
      //  设置宽
      this.change("width","marginLeft");
    }else if(this.direction == "y"){
      //  设置高
      this.change("height","marginTop");
    }

  },
  change:function(attr1,attr2){
    var _this = this;
     // 定时器内容
     this.li_attr = parseInt(this.getAttr(attr1));
     this.ul.style[attr1] = this.li_num * this.li_attr + "px";

     setInterval(function() {
       // body...
       _this.index--;
       _this.ul.style[attr2] = _this.index + "px";
       if( Math.abs(_this.index) >= _this.li_attr ){
         _this.ul.appendChild(_this.ul.firstElementChild);
         _this.ul.style[attr2] = "0px";
         _this.index = 0;
       }
     }, _this.speed);

  },

  getAttr:function(attr){
     // 获取样式值的
     if (this.li[0].currentStyle) {
       return  this.li[0].currentStyle[attr]
     }else{
       return getComputedStyle(this.li[0],null)[attr]
     }
  }

};

new Scroll({
  el: "box1",
  direction: "x",
  speed: 50,
})


new Scroll({
  el: "box2",
  direction: "y",
  speed: 30,
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值