纯js实现淘宝商城轮播图
需求:
  循环⽆缝⾃动轮播3张图⽚,点击左右箭头可以⼿动切换图⽚,⿏标点击轮播图下⾯的⼩圆点会跳转到对应的第⼏张图⽚。⿏标放到轮播图的图⽚上时不再⾃动轮播,⿏标移开之后⼜继续轮播。
效果图:
下⾯是html代码:
<div id="box">
<div id="imgbox">
<div><img src="img/tu1.jpg" alt="" /></div>
<div><img src="img/tu2.jpg" alt="" /></div>
<div><img src="img/tu3.jpg" alt="" /></div>
</div>
<div class="yuandian">
<a href="#"class="xiaoyuan"></a>
<a href="#"class="xiaoyuan"></a>
<a href="#"class="xiaoyuan"></a>
</div>
<div id="jiantou">
<span id="jt_left"class="jiant"><</span>
<span id="jt_right"class="jiant">></span>
</div>
</div>
css代码:
* {
margin: 0;
padding: 0;
}
#box {
position: relative;
width: 520px;
height: 280px;
/*background-color: pink;*/
margin:100px auto;
overflow: hidden;
}
#imgbox {
position: absolute;
top: 0;
left: 0;
width: 99999px;
cursor: pointer;
height: 100%;
}
#imgbox img {
float: left;
}
.yuandian {
position: absolute;
left: 230px;
bottom: 20px;
width: 60px;
height: 15px;
border-radius: 20px;
background: rgba(255,255,255,.6);
}
.yuandian a {
float: left;
width: 10px;
height: 10px;
border-radius: 10px;
margin: 2px 00 7px;
background-color: white;
}
#jt_left {
left: 0;
border-top-right-radius:2em;
border-bottom-right-radius:2em;
}
#jt_left,
#jt_right {
js实现轮播图最简代码position: absolute;
top: 140px;
width: 35px;
height: 35px;
line-height: 35px;
cursor: pointer;
font-size: 18px;
text-align: center;
background: rgba(255,255,255,.6);
}
#jt_right {
right: 0;
border-top-left-radius:2em;
border-bottom-left-radius:2em;
}
js代码:
<script type="text/javascript">
//    获取⼩圆点
var xiaoyuan = ElementsByClassName("xiaoyuan"); //    获取装图⽚的盒⼦
var imgbox = ElementById("imgbox");
//    获取左右箭头
var jiantou = ElementsByClassName("jiant");
//⼩圆点控制图⽚
xiaoyuan[0].onclick = function () {
imgbox.style.left = 0;
}
xiaoyuan[1].onclick = function () {
imgbox.style.left = "-520px";
}
xiaoyuan[2].onclick = function () {
imgbox.style.left = "-1040px";
}
//左箭头控制图⽚
jiantou[0].onclick = function () {
if (imgbox.offsetLeft == 0) {
imgbox.style.left = "-1040px";
console.log(imgbox.offsetLeft);
} else {
imgbox.style.left = imgbox.offsetLeft + 520 + "px";
}
}
//右箭头控制图⽚
jiantou[1].onclick = function () {
if (imgbox.offsetLeft <= -1040) {
console.log(imgbox.offsetLeft);
imgbox.style.left = 0;
} else {
imgbox.style.left = imgbox.offsetLeft - 520 + "px";
}
}
//定时器控制图⽚轮播
var fun1 = function () {
if (imgbox.offsetLeft <= -1040) {
imgbox.style.left = 0;
} else {
imgbox.style.left = imgbox.offsetLeft - 520 + "px";
}
}
var t = setInterval(fun1, 2500);//fun1是你的函数
// ⿏标经过停⽌轮播
clearInterval(t) //关闭定时器
}
// ⿏标离开开启定时器
t=setInterval(fun1,2500)//重新开始定时器
}
</script>