原生js一行代码实现简易轮播图

时间:2023-03-08 17:37:55

这是一个简易的js无限循环轮播图,只用了一行js代码就实现了无限循环,记录一下三目运算符的伟大!

<!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;
}
ul,li{
list-style: none;
}
.container {
width: 600px;
height: 400px;
margin: 100px auto;
box-shadow: 0 0 5px green;
overflow: hidden;
}
.container .wrap {
width: 4200px;
height: 400px;
transition: 1s;
overflow: hidden;
}
.container .wrap li {
float: left;
width: 600px;
height: 400px;
box-shadow: 0 0 1px 1px #f60;
line-height: 400px;
text-align: center;
font-size: 50px;
}
</style>
</head>
<body>
<div class="container">
<ul class="wrap" style="margin-left:0px;">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
<script>
setInterval(()=>{
var wrap = document.querySelector('.wrap')
var left = parseInt(wrap.style.marginLeft)
wrap.style.marginLeft = left >= -2400 ? left - 600 + 'px' : '0px'
},2000)
</script>
</body>
</html>