js实现轮播图,鼠标放上去会跳相应页面,代码很简答,如下
htm部分:
<div id="tab">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div class="cont" style="display: block;"><img src="images/1.jpg" alt=""></div>
<div class="cont"><img src="images/2.jpg" alt=""></div>
<div class="cont"><img src="images/3.jpg" alt=""></div>
<div class="cont"><img src="images/4.jpg" alt=""></div>
</div>
css部分:
*{
margin: 0;
padding: 0;
}
#tab {
position: relative;
}
#tab ul {
overflow: hidden;
display: flex;
position: absolute;
left: 500px;
bottom: 10px;
}
.active {
background-color: #090909 !important;
}
#tab ul li {
width: 30px;
height: 30px;
line-height: 30px;
background-color: #FCBECD;
color: #fff;
list-style: none;
text-align: center;
margin-left: 10px;
}
#tab .cont {
display: none;
}
js部分:
<script type="text/javascript">
var oli = document.getElementsByTagName('li');
var ocont = document.getElementsByClassName('cont');
for (var i = 0; i < oli.length; i++) {
oli[i].index = i; //获取当前下标
oli[i].onmouseover = function () {//遍历所有
for (var j = 0; j < oli.length; j++) {
oli[j].className = "";//让所有li的class名为空
ocont[j].style.display = "none";//让所有div的display为空
}
a = this.index;//使自动播放顺序按鼠标划到当前的下标开始
this.className = "active";//使当前li的class为active
ocont[this.index].style.display = "block";//使当前对应的div的display为block
}
}
var a=0;
aa = setInterval(function () {//定时器
a++;
for(var b=0;b<oli.length;b++){//同上遍历
oli[b].className = "";
ocont[b].style.display = "none";
}
if(a>=4){//使下标不超过3
a=0;
}
oli[a].className="active";
ocont[a].style.display = "block";
}, 2000)
</script>
下面是简便原型方法写的轮播图,js部分不一样,其他都一样
<script type="text/javascript">
var oli = document.getElementsByTagName('li');
var ot = document.getElementsByClassName('cont');
function Aaa(ot, oli) {
this.ot = ot;
this.oli = oli;
}
var aa = null;
Aaa.prototype.bbb = function () {
for (var i = 0; i < this.oli.length; i++) {
this.oli[i].index = i;
this.oli[i].onmouseover = function () {
for (var j = 0; j < oli.length; j++) {
oli[j].className = "";
ot[j].style.display = "none";
}
a = this.index;
this.className = "active";
ot[this.index].style.display = "block";
}
}
var a = 0;
aa = setInterval(function () {
a++;
for (var b = 0; b < this.oli.length; b++) {
this.oli[b].className = "";
this.ot[b].style.display = "none";
}
if (a >= 4) {
a = 0;
}
this.oli[a].className = "active";
this.ot[a].style.display = "block";
}, 2000)
}
var cc = new Aaa(ot, oli);
cc.bbb();
</script>