实现单向轮播的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<style>
*{
margin: 0px;
padding: 0px;
list-style: none;
}
.box{
width: 800px;
height: 800px;
border: 2px solid black;
position: relative;
margin: auto;
overflow: hidden;
}
.box2 {
width: 100%;
height: 100%;
left: 0px;
top: 0px;
}
.box2 li{
width: 100%;
height: 100%;
position: absolute;
font-size: 100px;
text-align: center;
line-height: 800px;
}
.box2 li img{
width: 100%;
height: 100%;
}
p{
width: 100%;
height: 30px;
}
button{
display:block;
margin-left:-100 px;
width: 80px;
height: 30px;
background-color: #ccc;
border: 1px solid bisque;
margin: auto;
cursor: pointer;
}
/* 但屏幕小于五百时改变样式 */
@media (max-width: 500px){
.box{
width: 400px;
height: 400px;
}
.box2 li{
line-height: 400px;
}
}
</style>
</head>
<body>
<div class="box">
<ul class="box2">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<p><button class="btn1">下一张</button></p>
<script>
//当浏览页面发生改变时触发
$(window).resize(function() {
window.location.reload()//页面刷新
});
var $width=$(".box").width() //获取类名为box元素的宽度
var length=$("li").length //获取li元素的长度
for(var i=0;i<length;i++){//给每个li元素定位
var left=i* $width
$(".box li").eq(i).css({"left":left+"px"})
}
var index=0
var num=0
var time=2000
var c=0
var timer=setInterval(timeCount,time)//定时器
//实现循环的函数
function timeCount(){
c++
if(c<length){
var left1=0
for(var index=0;index<length;index++){
// left1=index*200-200*c
left1= $width*(index-c)
$(".box li").eq(index).animate({left:left1+"px",top:"0"},1000)
}
if(c==length-1){
for(var i=1;i<length;i++){
var left=i* $width
$(".box li").eq(i-1).animate({"left":left+"px"},0)
}
}
}
if(c==length){
for(var index1=0;index1<length;index1++){
if(index1<length-1){
var left1= $width*index1
$(".box li").eq(index1).animate({"left":left1+"px",top:"0"},1000)
}else{
var left2=index1* $width
$(".box li").eq(length-1).animate({left:-$width+"px",top:"0"},1000)
$(".box li").eq(length-1).animate({left:left2,top:"0"},0)
c=0
}
}
}
}
//添加按钮事件,点击按钮触发
$(".btn1").click(function(){
timeCount();
clearInterval(timer)
})
</script>
</body>
</html>