滾動(dòng)輪播圖原理:
以本文為例,想要實(shí)現(xiàn)視覺(jué)上的無(wú)縫隙滾動(dòng)輪播,就需要在第四張圖后捆毫,再添加第一張和第二張圖,因?yàn)楸疚牡陌咐峭瑫r(shí)顯示兩張圖片冲甘,如果只顯示一張圖绩卤,那么就在最后一張圖后添加第一張圖就可以了途样。
接下來(lái),我們一起來(lái)看代碼濒憋,其它解釋會(huì)在代碼注釋里有所體現(xiàn)何暇。
<!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;
}
/* 滾動(dòng)的不是圖片本身,而是包裹著圖片的盒子 */
.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; // 定義定時(shí)器名字
var count = 0; // 控制左偏移量
timer = setInterval(autoPlay, 30); // 開(kāi)啟定時(shí)器
function autoPlay() {
count--;
count <= -1200 ? count = 0 : count; // 當(dāng)count小于-1200時(shí)凛驮,讓count等于0裆站,否則,繼續(xù)--
ul.style.left = count + "px";
}
scroll.onmouseover = function () { // 鼠標(biāo)懸浮停止定時(shí)器
clearInterval(timer);
}
scroll.onmouseout = function () {
timer = setInterval(autoPlay, 30); // 鼠標(biāo)離開(kāi)開(kāi)啟定時(shí)器
}
</script>
</body>
</html>