高级无缝滚动轮播图
改进:
- 折返点计算需要通过 js 自动计算.
取消<ul>
的width
属性, 通过offsetWidth
返回宽度(包括边框).
var back = -munit.offsetWidth;
- 自动生成另一组对应的图片结构
<li>
.
munit.innerHTML = munit.innerHTML + munit.innerHTML;
注意:
如果没有onload, offsetWidth返回的值是错误的. 图片还没有加载完就会先执行后面的JavaScript代码, 导致offsetWidth的值小于<ul>
的宽度.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.scroll {
position: relative;
width: 830px;
height: 130px;
border: 10px solid #000;
margin: 100px auto;
overflow: hidden;
}
.scroll .inner {
position: relative;
width: 5000px;
}
.scroll ul {
position: absolute;
top: 0;
left: 0;
height: 130px;
list-style: none;
}
.scroll ul li {
float: left;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="scroll" id="scroll">
<div class="inner">
<ul id="munit">
<li><img src="images/shuzi/0.png" alt="" /></li>
<li><img src="images/shuzi/1.png" alt="" /></li>
<li><img src="images/shuzi/2.png" alt="" /></li>
<li><img src="images/shuzi/3.png" alt="" /></li>
<li><img src="images/shuzi/4.png" alt="" /></li>
<li><img src="images/shuzi/5.png" alt="" /></li>
<li><img src="images/shuzi/6.png" alt="" /></li>
</ul>
</div>
</div>
<script>
onload = function () {
var scroll = document.getElementById("scroll");
var munit = document.getElementById("munit");
console.log(scroll);
console.log(munit);
var back = -munit.offsetWidth;
console.log(back);
//生成两倍的li标签
munit.innerHTML = munit.innerHTML + munit.innerHTML;
//初始位置 (自己进行滚动播放)
var nowLeft = 0;
var timer;
timer = setInterval(run, 10);
//鼠标移上 scroll 元素,让运动停止
scroll.onmouseover = function () {
clearInterval(timer);
};
//鼠标离开 scroll 元素,让运动重新开始
scroll.onmouseout = function () {
timer = setInterval(run, 10);
};
//运动函数
function run() {
//nowLeft自减
nowLeft -= 2;
// 每次都要判断,是否走到了折返点,如果走到了,瞬间切换到 0
if (nowLeft <= back) {
nowLeft = 0;
}
munit.style.left = nowLeft + "px";
}
}
</script>
</body>
</html>