十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这篇文章给大家分享的是有关js如何实现图片首尾平滑轮播的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
10年积累的成都做网站、网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有扬州免费网站建设让你可以放心的选择与我们合作。
首先给出HTML代码,要注意轮播图片表(#list)末尾加上第一个图片1.jpg,在首部加上最后一个图片5.jpg。
首尾轮播
接下来给出css和js代码,大家可以酌情根据图片的大小、数量、宽度,调整container、list的参数,这也是封装JS所要考虑的参数。
*{
margin: 0;
padding: 0;
}
#container{
height: 400px;
width: 500px;
margin: 0 auto;
position: relative;
overflow: hidden;
border: 1px solid black;
}
#list>div {
float: left;
}
#list{
position: absolute;
height: 400px;
width: 3600px;
}
#list img{
height: 400px;
width: 500px;
}
.arrow {
user-select:none;
position: absolute;
top:150px;
z-index: 2;
background-color: #aaa;
height: 100px;
width: 80px;
cursor: pointer;
opacity: 0.5;
display: none;
line-height: 100px;
text-align: center;
color: #222;
font-size: 3em;
}
#container:hover .arrow{
display: block;
}
#prev{
left:20px;
}
#next{
right: 20px;
}在JS中,我们可以通过改变speed变量来控制图片切换的速度....这里用的是 element.style.transition来控制的过渡效果.
window.onload=function(){
var container = document.getElementById('container');
var list = document.getElementById('list');//获取图片容器
var prev = document.getElementById('prev');//向前按钮
var next = document.getElementById('next');//向后按钮
var nowP = 1; //显示位置
var judge = null; //执行权
var speed = 0.1; // 切换速度 秒
prev.onclick=function(){
if(!judge){
judge = setTimeout(function(){
if(nowP==1){setTimeout(function(){
list.style.transition="left 0s";
list.style.left = "-2500px";
nowP = 5;},speed*1000);} //当到达图片表左边缘时与动画同步切换
list.style.transition = "left "+speed+"s";
move(500);
nowP--;
judge = null;
},speed*1000);
}
};
next.onclick=function(){
if(!judge){
judge = setTimeout(function(){
if(nowP==5){setTimeout(function(){
list.style.transition="left 0s";
list.style.left = "-500px";
nowP = 1;},speed*1000);} //当到达图片表右边缘时与动画同步切换
list.style.transition = "left "+speed+"s";
move(-500);
nowP++;
judge = null;
},speed*1000);
}
};
function move(num){
var term = parseInt(list.style.left) + num ;
list.style.left = term+"px";
}
var roll= setInterval(function(){
next.onclick();
},2000);
container.onmouseenter=function(){
clearInterval(roll);
};
container.onmouseleave=function()
{
roll=setInterval(function(){
next.onclick();
},2000);
};
};下面是一个演示demo,简单来说原理就是在切换到图片表首和表尾的动画开始时,设置一个延迟执行时间与动画过渡时间相同的setTimeout函数来执行瞬间切换,再通过节流来保证最大的切换速度(speed)。

感谢各位的阅读!关于“js如何实现图片首尾平滑轮播”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!