当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现横向跑马灯效果代码

JS实现横向跑马灯效果代码

2020年05月11日  | 移动技术网IT编程  | 我要评论

首先我们需要一个html代码的框架如下:

<div style="position: absolute; top: 0px; left: 168px; width: 100%; margin-left: auto; margin-right: auto; height: 47px; border: 0px solid red; overflow: hidden;">
    <ul id="synoticeulnew" style="margin: 0px;left:0; top:0;margin-bottom:0px;width:100%;height:47px;position:absolute;">

    </ul>
  </div>

我们的目的是实现ul中的内容进行横向的一点一点滚动。ul中的内容应该是动态的。于是应该发送ajax来进行内容的获取拼接。

$.ajax({
      type:"post",
      datatype:"json",
      url:"${contextpath}/indexpage/getsynoticeinfo",
      success:function(result){
        var totalstr = "";
        if(result.length>0){
          for(var i=0 ; i<result.length;i++){
            str = "<li style=\"list-style: none;display:inline-block;float:left;height:47px;padding-right:50px;line-height:47px;\">"+
             "<a style=\"color:white;\" class=\"sstznoticestyle\">"+result[i].peoplename+"</a>"+
             "</li>";
            totalstr +=str;
          }
        }
        $("#synoticeulnew").empty();
        $('#synoticeulnew').html(totalstr);
        syrunhorselight();
      }
    });

拼接li时候有个class为sstznoticestyle。其样式如下:

.sstznoticestyle{
  color:white; font-size:16px;text-decoration:none;
}
.sstznoticestyle:hover{
  color:white; font-size:16px;text-decoration:none;
}

ajax调用syrunhorselight函数,函数如下:

function syrunhorselight() {
    if (sytimer != null) {
      clearinterval(sytimer);
    }
    var oul = document.getelementbyid("synoticeulnew");
    if(oul != null){
      oul.innerhtml += oul.innerhtml;
      oul.innerhtml += oul.innerhtml;
      oul.innerhtml += oul.innerhtml;
      var lis = oul.getelementsbytagname('li');
      var listotalwidth = 0;
      var resetwidth = 0;
      for (var i = 0; i < lis.length; i++) {
        listotalwidth += lis[i].offsetwidth;
      }
      for (var i = 1; i <= lis.length / 4; i++) {
        resetwidth += lis[i].offsetwidth;
      }
      oul.style.width = listotalwidth + 'px';
      var left = 0;
      sytimer = setinterval(function() {
        left -= 1;
        if (left <= -resetwidth) {
          left = 0;
        }
        oul.style.left = left + 'px';
      }, 20)
      $("#synoticeulnew").hover(function() {
        clearinterval(sytimer);
      }, function() {
        clearinterval(sytimer);
        sytimer = setinterval(function() {
          left -= 1;
          if (left <= -resetwidth) {
            left = 0;
          }
          oul.style.left = left + 'px';
        }, 20);
      })
    }
  }

跑马灯效果就此实现。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网