滾動輪播圖原理:
以本文為例,想要實現視覺上的無縫隙滾動輪播,就需要在第四張圖后,再添加第一張和第二張圖,因為本文的案例是同時顯示兩張圖片,如果只顯示一張圖,那么就在最后一張圖后添加第一張圖就可以了。
接下來,我們一起來看代碼,其它解釋會在代碼注釋里有所體現。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
/* 去除圖片邊距 */
img {
vertical-align: top;
}
.box {
width: 600px;
height: 200px;
margin: 100px auto;
overflow: hidden;
position: relative;
}
.box ul li {
float: left;
}
/* 滾動的不是圖片本身,而是包裹著圖片的盒子 */
.box ul {
width: 400%;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="box" id="scroll">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
var scroll = document.getElementById("scroll");
var ul = scroll.children[0];
var timer = null; // 定義定時器名字
var count = 0; // 控制左偏移量
timer = setInterval(autoPlay, 30); // 開啟定時器
function autoPlay() {
count--;
count <= -1200 ? count = 0 : count; // 當count小于-1200時,讓count等于0,否則,繼續(xù)--
ul.style.left = count + "px";
}
scroll.onmouseover = function () { // 鼠標懸浮停止定時器
clearInterval(timer);
}
scroll.onmouseout = function () {
timer = setInterval(autoPlay, 30); // 鼠標離開開啟定時器
}
</script>
</body>
</html>