一个项目中需要用到类似的功能,自己手写一个轮播切换,不足之处见谅。代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.navUl{
border: 1px solid #ddd;
overflow: hidden;
}
.navUl li{
list-style: none;
float: left;
width: auto;
height: 30px;
line-height: 30px;
padding: 0 10px;
cursor: pointer;
}
.navUl li.activeLi{
background: rgb(155, 155, 247);
color: #fff;
}
</style>
</head>
<body>
<ul class="navUl js-navUl">
<li class="activeLi">tab1</li>
<li>tab2</li>
<li>tab3</li>
<li>tab4</li>
<li>tab5</li>
</ul>
<div>
<div id="tabCon0">
tab0内容
</div>
<div id="tabCon1" style="display:none">
tab1内容
</div>
<div id="tabCon2" style="display:none">
tab2内容
</div>
<div id="tabCon3" style="display:none">
tab3内容
</div>
<div id="tabCon4" style="display:none">
tab4内容
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
window.onload=function(){
var autoTab = setInterval( changeTab,2000);
$('.js-navUl').hover(
function () {
clearInterval(autoTab);
},
function () {
autoTab = setInterval( changeTab,2000);
});
var tabIndex=0;
function changeTab(){
$(".js-navUl li").eq(tabIndex).addClass("activeLi").siblings().removeClass("activeLi");
if($("#tabCon"+tabIndex)){
$("#tabCon"+tabIndex).show().siblings().hide();
}
tabIndex++;
if(tabIndex==5){
tabIndex=0;
}
}
$(".js-navUl li").on("click",function(){
var ind=$(this).index();
if($("#tabCon"+ind)){
$("#tabCon"+ind).show().siblings().hide();
}
if(ind!=4){
tabIndex=ind+1;
}else{
tabIndex=0;
}
$(this).addClass("activeLi").siblings().removeClass("activeLi");
});
}
</script>
</body>
</html>
样式什么的自己修改即可