效果:
需求:
1.记录循环滚动;
2.每组记录之间不能有留白;
3.每条记录上移到容器的顶部时要停顿一下;
4.鼠标移入容器时停止滚动,移出时继续滚动。
曾想用的实现方法:
1.使用Marquee:本来想用Marquee搞定,使用十分方便,但不满足需求2,3,加上只能用于IE浏览器。。。。。。。。
2.使用Jquery:我没有学过Jquery,只是简单调用同事的方法,但发现居然出现语法错误,同事也只是从网上拷过来不懂得哪里出错。。。。。。
于是只好硬着头皮自己写一个吧!
我的思路是:当最顶的记录完全移出容器时,把该记录移动到所有记录的底部
(图很丑但很温柔^_^)
下面是实现:(ie6、7、8,chrome都OK!)
css文件
<style type="text/css"> #divContainer{ width:110px; height:100px; overflow:hidden; border:none 0;/*如果不设置IE上border虽然看不到但宽度依然为1px*/ } .item{ position:relative; border:none 0;/*原因同上*/ word-break:break-all; word-wrap:break-word; line-height:25px; } </style>
AI 代码解读
html:
<div id="divContainer"> <div class="item" style="top:0;color:orange">1.abcdefghijklmnopqrstuvwsyz</div> <div class="item" style="top:0;color:blue">2.0123456789</div> <div class="item" style="top:0;color:red">3.一行中文字符</div> <div class="item" style="top:0;color:green">4.多行中文字符,今天天气真好啊!!</div> </div>
AI 代码解读
注意:每条记录的div必须在内嵌的style中设定top为0,否则在js中获取的是空字符串。
js:
<script type="text/javascript"> function MessageLooper(){ var divs = document.getElementById("divContainer").getElementsByTagName("div"); for(var i=0;i<divs.length;++i) { divs[i].style.top=(parseInt(divs[i].style.top.replace("px"))-1)+"px"; } if(divs[0].offsetHeight+parseInt(divs[0].style.top.replace("px"))<0) { var divs1 = divs[0]; for(var j=1;j<divs.length;++j) { divs[j].style.top=(parseInt(divs[j].style.top.replace("px"))+divs1.offsetHeight+1)+"px"; } document.getElementById("divContainer").removeChild(divs1); divs1.style.top="0" ; document.getElementById("divContainer").appendChild(divs1); clearInterval(setupML); toML=setTimeout("setupML=setInterval(MessageLooper,80);",800);/*逐条记录停顿*/ } } /*完成需求4的功能*/ if(document.getElementById("divContainer").childNodes.length!=0){ setupML = setInterval(MessageLooper,80); document.getElementById("divContainer").onmouseover=function(){clearInterval(setupML);if(typeof(toML)!="undefined")clearTimeout(toML)} document.getElementById("divContainer").onmouseout=function(){setupML=setInterval(MessageLooper,80)} } </script>
AI 代码解读
注意点:
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加上头元素的高度。