javascript实例:逐条记录停顿的走马灯

效果:

需求:

1.记录循环滚动;

2.每组记录之间不能有留白;

3.每条记录上移到容器的顶部时要停顿一下;

4.鼠标移入容器时停止滚动,移出时继续滚动。

曾想用的实现方法:

1.使用Marquee:本来想用Marquee搞定,使用十分方便,但不满足需求2,3,加上只能用于IE浏览器。。。。。。。。

2.使用Jquery:我没有学过Jquery,只是简单调用同事的方法,但发现居然出现语法错误,同事也只是从网上拷过来不懂得哪里出错。。。。。。

于是只好硬着头皮自己写一个吧!

我的思路是:当最顶的记录完全移出容器时,把该记录移动到所有记录的底部

(图很丑但很温柔^_^)

下面是实现:(ie6、7、8,chrome都OK!)

css文件

 1 <style type="text/css">
2 #divContainer{
3 width:110px;
4 height:100px;
5 overflow:hidden;
6 border:none 0;/*如果不设置IE上border虽然看不到但宽度依然为1px*/
8 }
9 .item{
10 position:relative;
11 border:none 0;/*原因同上*/
12 word-break:break-all;
13 word-wrap:break-word;
14 line-height:25px;
15 }
16 </style>

html:

1 <div id="divContainer">
2 <div class="item" style="top:0;color:orange">1.abcdefghijklmnopqrstuvwsyz</div>
3 <div class="item" style="top:0;color:blue">2.0123456789</div>
4 <div class="item" style="top:0;color:red">3.一行中文字符</div>
5 <div class="item" style="top:0;color:green">4.多行中文字符,今天天气真好啊!!</div>
6 </div>

注意:每条记录的div必须在内嵌的style中设定top为0,否则在js中获取的是空字符串。

js:

 1 <script type="text/javascript">
2 function MessageLooper(){
3 var divs = document.getElementById("divContainer").getElementsByTagName("div");
4 for(var i=0;i<divs.length;++i)
5 {
6 divs[i].style.top=(parseInt(divs[i].style.top.replace("px"))-1)+"px";
7 }
8 if(divs[0].offsetHeight+parseInt(divs[0].style.top.replace("px"))<0)
9 {
10 var divs1 = divs[0];
11 for(var j=1;j<divs.length;++j)
12 {
13 divs[j].style.top=(parseInt(divs[j].style.top.replace("px"))+divs1.offsetHeight+1)+"px";
14 }
15 document.getElementById("divContainer").removeChild(divs1);
16 divs1.style.top="0" ;
17 document.getElementById("divContainer").appendChild(divs1);
18
19 clearInterval(setupML);
20 toML=setTimeout("setupML=setInterval(MessageLooper,80);",800);/*逐条记录停顿*/
21 }
22 }
  /*完成需求4的功能*/
23 if(document.getElementById("divContainer").childNodes.length!=0){
24 setupML = setInterval(MessageLooper,80);
25 document.getElementById("divContainer").onmouseover=function(){clearInterval(setupML);if(typeof(toML)!="undefined")clearTimeout(toML)}
26 document.getElementById("divContainer").onmouseout=function(){setupML=setInterval(MessageLooper,80)}
27 }
28 </script>

注意点:

1.offsetTop和style.top的区别:

(1)offsetTop指的是元素上外边框离父容器上外边框的Y轴距离(单位px);style.top指的是元素上外边框离自己原来位置上外边框的Y轴距离(单位px)。

当容器的position设置为relative时子元素的offsetTop才是子元素离容器上边框的距离,否则为子元素离浏览器工作区上边框的距离。

(2)offsetTop为只读属性,值为纯数字;style.top为可读可写属性,值如12px这样的字符串。

因为offsetTop为只读,最终控制元素位置要用style.top,而两者表达的含义又有所区别,所以这里我直接用style.top来获取定位和设置定位。

2.因为要将头元素移动到其他兄弟元素的后面,这个移动过程会使其他兄弟元素的定位发生变化,均向上移动了头元素高度的距离,所以要为各个兄弟元素的style.top加上头元素的高度。

大家如果有更好的方法欢迎共享哦!!

欢迎添加我的公众号一起深入探讨技术手艺人的那些事!

如果您觉得本文的内容有趣就扫一下吧!捐赠互勉!
  

原文地址:https://www.cnblogs.com/fsjohnhuang/p/2288626.html