javascript无缝滚动图的制作方法。

来源:互联网 发布:网络电视机顶盒系统 编辑:程序博客网 时间:2024/05/17 08:16
代码部分:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">*{margin: 0;padding: 0;}ul,li{list-style: none;}#box{height: 116px;width: 740px;border: 1px solid #000;margin: 100px;position: relative;overflow: hidden;}#box ul{position: absolute;left: 0;top: 0;}#box ul li{float: left;width: 185px;height: 116px;}#box ul li img{display: block;width: 185px;height: 116px;}#direction p{width: 100px;height: 40px;line-height: 40px;text-align: center;background: green;color: #fff;float: left;margin-right: 5px;}</style><script type="text/javascript">window.onload=function(){var oBox=document.getElementById('box');var oUl=oBox.getElementsByTagName('ul')[0];var aLi=oUl.getElementsByTagName('li');var oToleft=document.getElementById('to_left');var oToright=document.getElementById('to_right');var speed=-2;oUl.innerHTML=oUl.innerHTML+oUl.innerHTML;oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';function toleft(){if(-oUl.offsetLeft>oUl.offsetWidth/2){oUl.style.left='0px';}if(oUl.offsetLeft>0){oUl.style.left=-oUl.offsetWidth/2+'px';}oUl.style.left=oUl.offsetLeft+speed+'px';}oToleft.onclick=function(){speed=-2;}oToright.onclick=function(){speed=2;}setInterval(toleft,50);}</script></head><body><div id="box"><ul><li><img src="img/a1.jpeg" alt="" /></li><li><img src="img/a2.jpeg" alt="" /></li><li><img src="img/a3.jpeg" alt="" /></li><li><img src="img/a4.jpeg" alt="" /></li></ul></div><div id="direction"><p id="to_left">向左</p><p id="to_right">向右</p></div></body></html>

代码实现的效果是通过两个按钮,向左、向右实现对滚动图的滚动方向的控制。

1、如何让图片动起来?

   解决动的问题,一定要和时间有关,JS中主要有两个函数setTimeout()和setInterval(),设定图片为绝对定位,然后使用定时器使图片的left值不断增加或减少.

2、怎样让图片循环无缝滚动?

 关键是通过offsetLeft、offsetWidth属性的判定,寻找图片循环滚动的临界点。使用两组图片,当图片运动过半时,拉回即left归零滚动继续,保证视觉效果无间断.


判定方法:

function toleft(){if(-oUl.offsetLeft>oUl.offsetWidth/2){//往左边走,达到临界点就扯回来oUl.style.left='0px';}if(oUl.offsetLeft>0){//往右边走,达到临界点就扯回来oUl.style.left=-oUl.offsetWidth/2+'px';}oUl.style.left=oUl.offsetLeft+speed+'px';}

3、控制左右方向,控制left值增加量的征服值即可实现。

知识点:

1.属性offsetLeft offsetTop offsetWidth offsetHeight  分别表示对象的左边距、上边距、宽和高,均为数值,设置时注意尾部 +‘px’

2.oUl.innerHTML+=oUl.innerHTML;   将对象的内容复制一倍

3.定时器setInterval(函数,时间间隔)     每隔一定时间间隔运行一次函数

   setTimeout(函数,时间)  加载后时间间隔后只运行一次函数,可起到延时效果

   clearInterval( 定时器对象)   关闭定时器。

二、还有一种方法是利用scrollLeft实现。

JS代码为:
 <script language="javascript"> var speed=20; var tab=document.getElementById("demo"); var tab1=document.getElementById("demo1"); var tab2=document.getElementById("demo2"); tab2.innerHTML=tab1.innerHTML; //通过赋值获得tab1的值 function marquee(){  if(tab2.offsetWidth-tab.scrollLeft<=0) //当tab的移动宽度大于等于demo1的时候,scrollLeft为0,也就是恢复到未移动前的情况,继续移动  {tab.scrollLeft=0} else {tab.scrollLeft++;} //图片层不断的往left移动 } var timer=setInterval(marquee,speed); //定时器  tab.onmouseover =function(){clearInterval(timer)}; //鼠标经过容器的时候清除定时器 tab.onmouseout =function(){timer=setInterval(marquee,speed);} //鼠标移开容器的时候开始定时器</script>  




0 0