原理
1. 轮播图主要是利用了 overflow:hidden 与 position:absolute;这两个属性
2. 通过overflow:hidden;隐藏图片,通过position:absolute的left或者right显示隐藏的图片
CSS
<style>
*{
margin: 0;
padding: 0;
}
.wrapper{
position: relative;
font-size:30px;
text-align: center;
line-height: 200px;
width:400px;
height:200px;
margin:100px;
overflow: hidden;
}
ul{
position: absolute;
width:1600px;
height:200px;
padding: 0;
list-style:none;
}
li{
width:400px;
height:100%;
float: left;
}
li:nth-child(1){
background:orange;
}
li:nth-child(2){
background: aqua;
}
li:nth-child(3){
background: chartreuse;
}
li:nth-child(4){
background: hotpink;
}
.prev,.next{
position: absolute;
top:50%;
transform: translateY(-50%);
font-size:30px;
text-align: center;
line-height: 30px;
width:30px;
height:30px;
background: #e0f0e9;
border-radius:50%;
}
.prev{
left:10px;
}
.next{
right:10px;
}
.dots{
position: absolute;
left:50%;
bottom: 15px;
transform: translateX(-50%);
}
.dots div{
width:20px;
height:20px;
background:white;
border-radius: 50%;
float: left;
margin: 0 5px;
}
.dots>div:nth-child(1){
background:#f20c00;
}
</style>
HTML
<div class="wrapper">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
<div class="prev"><</div>
<div class="next">></div>
<div class="dots">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
JavaScript
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script>
$(function(){
let init = 0;、
let pos
$('.prev').on('click',function(){
if(init>0)
init -=1;
pos = -init * 400
console.log(init)
$('ul').css({
left:`${pos}px`
})
$('.dots>div').eq(init).css({
background:'#f20c00'
})
$('.dots>div').eq(init+1).css({
background:'white'
})
})
$('.next').on('click',function(){
if(init<3)
init +=1;
pos = -init * 400
console.log(init)
$('ul').css({
left:`${pos}px`
})
$('.dots>div').eq(init).css({
background:'#f20c00'
})
$('.dots>div').eq(init-1).css({
background:'white'
})
})
})
</script>