setInterval制作走马灯
时间: 2023-12-10 16:36:03 浏览: 137
以下是使用setInterval制作走马灯的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>走马灯</title>
<style>
#container {
width: 300px;
height: 100px;
overflow: hidden;
position: relative;
}
#list {
position: absolute;
left: 0;
top: 0;
width: 900px;
height: 100px;
}
#list img {
float: left;
width: 300px;
height: 100px;
}
</style>
</head>
<body>
<div id="container">
<div id="list">
<img src="image1.jpg" alt="image1">
<img src="image2.jpg" alt="image2">
<img src="image3.jpg" alt="image3">
</div>
</div>
<script>
var container = document.getElementById('container');
var list = document.getElementById('list');
var imgs = list.getElementsByTagName('img');
var index = 0;
var timer = setInterval(function() {
index++;
if (index >= imgs.length) {
index = 0;
}
list.style.left = -index * 300 + 'px';
}, 2000);
container.onmouseenter = function() {
clearInterval(timer);
};
container.onmouseleave = function() {
timer = setInterval(function() {
index++;
if (index >= imgs.length) {
index = 0;
}
list.style.left = -index * 300 + 'px';
}, 2000);
};
</script>
</body>
</html>
```
该示例代码中,使用setInterval函数实现了轮播图的自动播放,每隔2秒钟切换一张图片。同时,当鼠标移入轮播图区域时,清除定时器,停止自动播放;当鼠标移出轮播图区域时,重新设置定时器,继续自动播放。
阅读全文