横向轮播图的封装
本人原生手写的封装!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>横向轮播图的封装</title>
<style>
*{margin: 0;padding: 0;}
a{text-decoration: none;}
.container{
position: relative;
width: 1800px;
height: 400px;
margin:100px auto 0 auto;
/* background-color: pink; */
box-shadow: 0 0 5px green;
overflow: hidden;
}
.wrap{
position: absolute;
width: 4270px;
height: 300px;
z-index: 1;
margin-top: 50px;
}
.img{
float: left;
width: 600px;
height: 300px;
font-size: 100px;
line-height: 300px;
text-align: center;
margin-left: 10px;
}
.arrow{
position: absolute;
font-size: 50px;
border-radius: 50%;
top: 40%;
z-index: 2;
padding:0px 14px;
color: red;
background-color: rgba(0,0,0,0.2);
}
.arrow_left{
left: 10px;
}
.arrow_right{
right: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="wrap" style="left: -600px;">
<div class="img" style="background: cyan;">5</div>
<div class="img" style="background: red;">1</div>
<div class="img" style="background: orange;">2</div>
<div class="img" style="background: yellow;">3</div>
<div class="img" style="background: green;">4</div>
<div class="img" style="background: cyan;">5</div>
<div class="img" style="background: red;">1</div>
</div>
<a href="javascript:;" class="arrow arrow_left"><</a>
<a href="javascript:;" class="arrow arrow_right">></a>
</div>
</body>
<script>
var wrap = document.querySelector('.wrap');
var prev = document.querySelector('.arrow_left')
var next = document.querySelector('.arrow_right');
// console.log(wrap, prev, next);
prev.onclick = function () {
console.log('左');
prev_pic();
}
next.onclick = function () {
console.log('右');
next_pic();
}
// 点击下一张
function next_pic () {
var newLeft;
if(wrap.style.left === "-2400px"){
newLeft = 0;
}else{
newLeft = parseInt(wrap.style.left)-600;
}
wrap.style.left = newLeft + "px";
console.log(wrap.style.left);
}
// 点击上一张
function prev_pic () {
var newLeft;
if(wrap.style.left === "0px"){
newLeft = -2400;
}else{
newLeft = parseInt(wrap.style.left)+600;
}
wrap.style.left = newLeft + "px";
console.log(wrap.style.left);
}
// 希望轮播图自动播放
var timer = null;
function autoPlay () {
timer = setInterval(function () {
next_pic();
}, 1000)
}
autoPlay();
// 如果想要仔细看其中一个图片的时候,希望轮播图停止播放,只要clearInterval()即可
var container = document.querySelector('.container');
container.onmouseenter = function () {
clearInterval(timer);
}
container.onmouseleave = function () {
autoPlay();
}
</script>
</html>
浙公网安备 33010602011771号