今天学习了一个js实现图片的无缝轮播滚动来和打搅分享一下
大体效果如上图所示:就是4张图片一直在两个按钮之间来回滚动下面介绍一个实现原理。
实现4张图片在两个按钮之间来回滚动假设先向左滚动首先我们通过 oUl.innerHTML+=oUl.innerHTML; 使里面的长度加一倍这样保证能在第四幅图片出来后第一副图片也能接着出来。接下来就是要让他循环显示:这里要用到一个属性:oUl.offsetWidth ul的宽度当第四幅图片刚好滚出屏幕时,此时画面的显示效果和初始状态一模一样,我们让他回到初始状态即可
l-=g_iSpeed;
if(l<=-oUl.offsetWidth/2)
{
l+=oUl.offsetWidth/2;
}
l记录滚动长度 当第四幅图片刚好滚出屏幕时 此时l的数值刚好为总长的一半 我们让他加上一般回归到初始状态
向右同理js代码中有不再详细叙述
http://mp.weixin.qq.com/s/EIv2DvRExr0QqUej8hgH7w
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(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; }
.control { border-bottom: 1px solid #ccc; background: #eee; text-align: center; padding: 20px 0; display: none; }
js:
var g_bMoveLeft=true;
var g_oTimer=null;
var g_iSpeed=3;
window.οnlοad=function(){
var oDiv=document.getElementById('roll');
var oUl=oDiv.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
var aA=oDiv.getElementsByTagName('a');
oUl.innerHTML+=oUl.innerHTML;
oUl.style.width=aLi[0].offsetWidth*aLi.length+'px';
for (var i = 0; i <aLi.length; i++) {
aLi[i].οnmοuseοver=function(){
stopMove();
}
aLi[i].οnmοuseοut=function(){
startMove(g_bMoveLeft);
}
}
aA[0].οnmοuseοver=function ()
{
startMove(true);
};
aA[1].οnmοuseοver=function ()
{
startMove(false);
};
startMove(true);
};
function startMove(bLeft)
{
g_bMoveLeft=bLeft;
if(g_oTimer)
{
clearInterval(g_oTimer);
}
g_oTimer=setInterval(doMove, 30);
}
function stopMove()
{
clearInterval(g_oTimer);
g_oTimer=null;
}
function doMove()
{
var oDiv=document.getElementById('roll');
var oUl=oDiv.getElementsByTagName('ul')[0];
var aLi=oUl.getElementsByTagName('li');
var l=oUl.offsetLeft;
if(g_bMoveLeft)
{
l-=g_iSpeed;
if(l<=-oUl.offsetWidth/2)
{
l+=oUl.offsetWidth/2;
}
}
else
{
l+=g_iSpeed;
if(l>=0)
{
l-=oUl.offsetWidth/2;
}
}
oUl.style.left=l+'px';
}