美文网首页我爱编程
文字公告跑马灯

文字公告跑马灯

作者: Arya06 | 来源:发表于2018-08-08 18:25 被阅读0次

    主要通过jQuery使得所控制的元素动态向上滚动,关键点在于无限循环,这里需要使用setInterval方法来实现。

    原理

    1. 初始

    在包裹层cointainer里面嵌套了三个div, 这里wrapper是页面上的可视部分


    menu.saveimg.savepath20180808175837.jpg

    代码如下:

        <div class="wrapper">
            <div class="container">
              <div class="test">跑马灯1</div>
              <div class="test">跑马灯2</div>
              <div class="test">跑马灯3</div>
            </div>
        </div>
    

    2.让container向上滚动起来,滚动距离可自定义(这里设置为每一个div的高度)

    animate({ margin-top: "-40px" })

    menu.saveimg.savepath20180808181100.jpg

    3.让顶部div移动到底部,并设置setInterval,让其循环无限滚动

    menu.saveimg.savepath20180808182324.jpg

    完整代码:

    
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8"> 
    <title>jQuery向上滚动代码</title>
    <link href="css/index.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <style>
    .wrapper {
      height: 40px;
      margin: 0 auto;
      background: red;
      position: relative;
      margin-top: 200px;
      line-height: 40px;
      overflow: hidden;
    }
    
    .container {
      margin: 0 auto;
      width: 80px;
      line-height: 40px;
    }
    
    .test {
      height: 30px;
      line-height: 40px;
      font-size: 15px;
      padding: 5px 0;
    }
    
    </style>
    </head>
    <body>
      <div class="wrapper">
          <div class="container">
            <div class="test">跑马灯1</div>
            <div class="test">跑马灯2</div>
            <div class="test">跑马灯3</div>
          </div>
      </div>
    <script type="text/javascript"> 
      function autoScroll(obj) {  
          $('.container').animate({  
              marginTop : "-40px"  //包裹层向上移动
          },3000,function(){
        console.log($(this));
              $(this).css({marginTop : "0px"}).find(".test:first").appendTo(this);  //将顶部div移动到底部 (这里需注意将div位置还原到初始位置)
          })  
      }  
      $(function(){ 
          var scroll = setInterval('autoScroll(".wrapper")',1500);
           $(".wrapper").hover(function() {
              clearInterval(scroll);
           },function(){
              scroll=setInterval('autoScroll(".wrapper")',1500);
           });
      }); 
    </script> 
    </body>
    </html>
    
    
    

    相关文章

      网友评论

        本文标题:文字公告跑马灯

        本文链接:https://www.haomeiwen.com/subject/jxyxbftx.html