1.页面加载完成让图片实现无缝滚动
2.鼠标移入左右两个按钮实现图片滚动方向的改变
3.鼠标移入图片实现图片停止滚动,移出实现图片滚动
1.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="img/1.jpg" /></a> </li> <li> <a href="http://www.miaov.com/"><img src="img/2.jpg" /></a> </li> <li> <a href="http://www.miaov.com/"><img src="img/3.jpg" /></a> </li> <li> <a href="http://www.miaov.com/"><img src="img/4.jpg" /></a> </li> </ul> </div> </div>
2.Css样式代码
* { padding: 0; margin: 0; } li { list-style: none; } img { border: 0; } .roll { width: 698px; height: 108px; margin: 50px auto 0; position: relative; } .btn_left { display: block; width: 68px; height: 68px; background: url(img/btn.jpg) no-repeat -70px -69px; position: absolute; top: 20px; left: 1px; z-index: 1; } .btn_left:hover { background: url(img/btn.jpg) no-repeat -70px 0; } .btn_right { display: block; width: 68px; height: 68px; background: url(img/btn.jpg) no-repeat 1px -69px; position: absolute; top: 20px; right: 0; z-index: 1; } .btn_right:hover { background: url(img/btn.jpg) no-repeat 1px 0; } .roll .wrap { width: 546px; height: 108px; margin: 0 auto; position: relative; overflow: hidden; } .roll ul { position: absolute; top: 0px; left: 0px; } .roll li { float: left; width: 182px; height: 108px; text-align: center; } .roll li a:hover { position: relative; top: 2px; }
3.js实现代码
window.onload = function() { var oDiv = document.getElementById('roll');//获取div var oUl = oDiv.getElementsByTagName('ul')[0];//获取Ul var aLi = oUl.getElementsByTagName('li');//获取li var oBtn = oDiv.getElementsByTagName('a');//获取左右两边的按钮 var iSpeed = -5; var timer ="";//定时器 oUl.innerHTML += oUl.innerHTML; oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';//获取Ul的总长度 timer = setInterval(function() { oUl.style.left = oUl.offsetLeft + iSpeed + 'px';//动态获取ul的长度 if(oUl.offsetLeft<-oUl.offsetWidth/2){ oUl.style.left = '0px' }else if(oUl.offsetLeft>0){ oUl.style.left = -oUl.offsetWidth/2+'px' } }, 30) oBtn[0].onmouseover = function(){ iSpeed = -5; } oBtn[1].onmouseover = function(){ iSpeed = 5; } oUl.onmouseover = function(){ clearTimeout(timer); } oUl.onmouseout = function(){ timer = setInterval(function() { oUl.style.left = oUl.offsetLeft + iSpeed + 'px'; if(oUl.offsetLeft<-oUl.offsetWidth/2){ oUl.style.left = '0px' }else if(oUl.offsetLeft>0){ oUl.style.left = -oUl.offsetWidth/2+'px' } }, 30) } }
1.通过setInterval--开启定时器和clearTimeout--关闭定时器
2.通过改变距离左边的值来实现图片的滚动
3.通过innerHtml来获取ul中的值
4.offsetLeft---左边距 offsetWidth---宽度