首页 > 代码库 > 用 js封装以左右滑动的轮播图,调用任意

用 js封装以左右滑动的轮播图,调用任意

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.tab{
width: 500px;
height: 300px;
margin: 0 auto;
background: yellow;
position: relative;
overflow: hidden;
}
*{
margin: 0;
padding: 0;
}
ul,ol{
list-style: none;
}
ul{
width: 1500px;
transition: 1s;
}
ul li{
width: 500px;
height: 300px;
font-size: 20px;
color: white;
line-height: 300px;
text-align: center;
float: left;
}
ul li:nth-child(1){
background: red;
}
ul li:nth-child(2){
background: green;
}
ul li:nth-child(3){
background: blue;
}
ol {
width: 100%;
position: absolute;
top:0px;
left:0;
}
ol li{
width:33.3%;
height: 30px;
background: #ccc;
float: left;
font-size: 20px;
text-align: center;
line-height: 30px;
color: white;
border: 1px solid black;
box-sizing: border-box;
}
.active{
background: red;
}
</style>
</head>
<body>
<div class="tab" id="tab1">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
<div class="tab" id="tab2">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ol>
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ol>
</div>
</body>
<script>
function $(x) {
return document.querySelector(x);
}
function $s(x) {
return document.querySelectorAll(x);
}
function tab(id){
var btns=$s(id+" ol li");
var picbox=$(id+" ul");
var length=btns.length;
for(var i=0;i<length;i++){
btns[i].index=i;
btns[i].onclick=function(){
picbox.style.marginLeft=-500*this.index+"px";
for(var i=0;i<length;i++){
btns[i].className="";
}
btns[this.index].className="active";
}
}
}
tab("#tab1");
tab("#tab2");
</script>
</html>

用 js封装以左右滑动的轮播图,调用任意