无缝滚动
功能:向左滑、向右滑、鼠标移入滑动暂停、鼠标移出滑动继续。
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {padding: 0; margin: 0; }
#div1 {width: 1200px; height: 300px; background: red; margin: 100px auto; position: relative; overflow: hidden;}
#div1 ul {position: absolute; left: 0; top: 0;}
#div1 ul li {list-style: none; width: 300px; height: 300px; float: left;}
#div1 img {width: 100%;}
</style>
</head>
<body>
<input type="button" value="向左走" id="btn1">
<input type="button" value="向右走" id="btn2">
<div id="div1">
<ul>
<li><img src="img1.jpg"></li>
<li><img src="img2.jpg"></li>
<li><img src="img3.jpg"></li>
<li><img src="img4.jpg"></li>
</ul>
</div>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1')
var oUl = oDiv.getElementsByTagName('ul')[0]
var aLi = oUl.getElementsByTagName('li')
var oBtn1 = document.getElementById('btn1') //向左走
var oBtn2 = document.getElementById('btn2') //向右走
var timer = null
var turn = 5 //用来控制方向,-5向左 5向右
oUl.innerHTML += oUl.innerHTML //将li元素复制
oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';
function move() {
if (oUl.offsetLeft < -oUl.offsetWidth / 2) { //向左走,当滑动到一半时
oUl.style.left = '0px'
}
if (oUl.offsetLeft > 0) { //向右走
oUl.style.left = -oUl.offsetWidth / 2 + 'px'
}
oUl.style.left = oUl.offsetLeft + turn + 'px'
}
timer = setInterval(move, 30)
oDiv.onmouseover = function () {
clearInterval(timer)
}
oDiv.onmouseout = function () {
timer = setInterval(move, 30)
}
oBtn1.onclick = function(){
turn = -5
}
oBtn2.onclick = function(){
turn = 5
}
}
</script>
</body>