目标:使用实现Javascript实现多图的横向无缝滚动,左右各有箭头可控制滚动方向,鼠标滑过事滚动停止,鼠标离开滚动继续。拓展则垂直滚动。
思路:
1.图片运动,设定图片为绝对定位,然后使用定时器使图片的left值不断增加或减少
2.无缝循环,使用两组图片,当图片运动过半时,拉回即left归零滚动继续,保证视觉效果无间断
3.控制左右方向,控制left值增加量的征服值即可实现
4.鼠标悬停,设置onmouseover事件关闭定时器,鼠标移开则重启定时器
知识点:
1.属性offsetLeft offsetTop offsetWidth offsetHeight 分别表示对象的左边距、上边距、宽和高,均为数值,设置时注意尾部 +‘px’
2.oUl.innerHTML+=oUl.innerHTML; 将对象的内容复制一倍
3.定时器setInterval(函数,时间间隔) 每隔一定时间间隔运行一次函数
setTimeout(函数,时间) 加载后时间间隔后只运行一次函数,可起到延时效果
clearInterval( 定时器对象) 关闭定时器
HTML框架:
<div class="roll" id="roll"> <a href="javascript:void(0);" class="btn_left"></a> <a href="javascript:void(0);" class="btn_right"></a> <div class="wrap"> <ul> <li><a href="http://www.miaov.com/"><img src="images/1.jpg" /></a></li> <li><a href="http://www.miaov.com/"><img src="images/2.jpg" /></a></li> <li><a href="http://www.miaov.com/"><img src="images/3.jpg" /></a></li> <li><a href="http://www.miaov.com/"><img src="images/4.jpg" /></a></li> </ul> </div> </div>
注意外部盒子要设为相对定位,且overflow:hidden;,ul为绝对定位
.roll { width: 698px; height: 108px; margin: 50px auto 0; position: relative; } .btn_left { display: block; width: 68px; height: 68px; background: url(images/btn.jpg) no-repeat -70px -69px; position: absolute; top: 20px; left: 1px; z-index: 1; } .btn_left:hover { background: url(images/btn.jpg) no-repeat -70px 0; } .btn_right { display: block; width: 68px; height: 68px; background: url(images/btn.jpg) no-repeat 1px -69px; position: absolute; top: 20px; right: 0; z-index: 1; } .btn_right:hover { background: url(images/btn.jpg) no-repeat 1px 0; } .roll .wrap { width: 546px; height: 108px; margin: 0 auto; position: relative; overflow: hidden; } .roll ul { position: absolute; top: 0; left: 0; } .roll li { float: left; width: 182px; height: 108px; text-align: center; } .roll li a:hover { position: relative; top: 2px; }
window.onload=function() { var oDiv=document.getElementById('roll'); var oUl=oDiv.getElementsByTagName('ul')[0]; var aLi=oUl.getElementsByTagName('li'); var speed=-4; var oBtn1=oDiv.getElementsByTagName('a')[0]; var oBtn2=oDiv.getElementsByTagName('a')[1]; var roll_timer=null; oUl.innerHTML+=oUl.innerHTML; oUl.style.width=aLi[0].offsetWidth*aLi.length+'px'; roll_timer=setInterval(function(){ oUl.style.left=oUl.offsetLeft+speed+'px'; if(oUl.offsetLeft<-oUl.offsetWidth/2) { oUl.style.left=0+'px'; } else if(oUl.offsetLeft>(0)) { oUl.style.left=-oUl.offsetWidth/2+'px'; } },30); oBtn1.onmouseover=function() { speed=-4; } oBtn2.onmouseover=function() { speed=4; } oUl.onmouseover=function() { clearInterval(roll_timer); } oUl.onmouseout=function() { roll_timer=setInterval(function(){ oUl.style.left=oUl.offsetLeft+speed+'px'; if(oUl.offsetLeft<-oUl.offsetWidth/2) { oUl.style.left=0+'px'; } else if(oUl.offsetLeft>(0)) { oUl.style.left=-oUl.offsetWidth/2+'px'; } },30); } };
效果图: