当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生js实现公告滚动效果

原生js实现公告滚动效果

2019年01月07日  | 移动技术网IT编程  | 我要评论
本文实例为大家分享了js实现公告滚动展示的具体代码,供大家参考,具体内容如下 1.html结构 <body> <div id="notic

本文实例为大家分享了js实现公告滚动展示的具体代码,供大家参考,具体内容如下

1.html结构

<body>
 <div id="notice" class="notice">
  <ul id="noticelist">
   <li>我是公告1</li>
   <li>我是公告2</li>
   <li>我是公告3</li>
   <li>我是公告4</li>
  </ul>
 </div>
</body>

2.css样式

<style type="text/css">
  body,
  div,
  ul,
  li {
   margin: 0;
   padding: 0;
  }
  
  ul,
  li {
   list-style: none;
  }
  
  .notice {
   width: 300px;
   height: 30px;
   border: 1px solid black;
   text-align: center;
   overflow: hidden;
  }
  
  li {
   padding: 3px;
  }
 </style>

3.js行为

<script type="text/javascript">
  window.onload = function() {
   var notice = document.getelementbyid("notice");
   var noticelist = document.getelementbyid("noticelist");
 
   // 获取ul下第一个li元素,好计算li的高度,因为后面滚动的时候每次要滚动一个高度,这里li都是一样高的,
   // 所以获取第一个的高度就行了,不然要遍历获取每一个li的高度。
   var noticefirstitem = noticelist.queryselector("li");
 
   // 获取li的高度,这里获取的是offsetheight,关于js各种高度的定义可以注意以下
   var scrollheight = noticefirstitem.offsetheight;
   // 是否可以进行动画
   var opt = {
    animated: true,
    interval: 1000
   };
 
   notice.onclick = function() {
    // 动画之前首先重置
    // noticefirstitem.style.transition = "";
    noticefirstitem.style.margintop = 0;
    if (opt.animated) {
     opt.animated = false;
     animate(noticelist, scrollheight, opt);
    }
   };
  };
 
  // 动画函数,obj——要产生动画的对象,sheight——每次要滚动的距离,interval——多久滚动一次
  function animate(obj, sheight, option) {
   // 当滚到最后一条公告的时候就不用动画了。
   var stopheight = sheight - obj.scrollheight;
   var margintopnum = 0;
   var timer = setinterval(function() {
    margintopnum -= sheight;
    obj.style.margintop = margintopnum + "px";
    obj.style.transition = "margin-top 1.5s ease";
    // 注意这里的比较符号,前面得到的高度都进行四舍五入了
    if (margintopnum <= stopheight) {
     clearinterval(timer);
     // option.animated = true;
    }
   }, option.interval);
  }
 </script>

4.运行结果

 

动画在进行中时注意控制不能进行其他动画!

结束语:不要把动画想得很难,当你想实现复杂的动画时,比如jquery的animate方法,你可以先实现针对一个属性的动画,然后再想办法扩展到多个属性(即以对象方式去传参,然后遍历对象中的每个样式属性,然后给每个样式属性添加动画)。以前都是用js去实现每一帧每一帧的移动,即在肉眼无法反应过来的时间里产生移动,这样就能产生连续移动的效果,现在css3出来了,可以方便的利用css3来实现过渡效果了,而不用复杂的js来实现了。这个真的太棒了。

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网