<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>走马灯</title>
<style>
#carousel-container {
/*overflow: auto; !*设置为auto可以更直观的理解该方法的原理:即用js滚动元素,当超过某一数值时,滚动条复位,重复循环来达到走马灯的效果*!*/
overflow: hidden; /* 隐藏滚动条,走马灯效果更好*/
white-space: nowrap;
}
#carousel-container > div{
display: inline-block;
width: 100px;
height: 100px;
}
#carousel-container .first_red{
background-color: red;
}
#carousel-container .second_orange{
background-color: orange;
}
#carousel-container .third_yellow{
background-color: yellow;
}
#carousel-container .four_green{
background-color: green;
}
#carousel-container .five_blue{
background-color: blue;
}
#carousel-container .six_indigo{
background-color: indigo;
}
#carousel-container .seven_violet{
background-color: violet;
}
#carousel-container .eight_white{
background-color: #c4a3a3;
}
#carousel-container .nine_black{
background-color: black;
}
</style>
<script type="text/javascript">
const delayTime = 1 // 控制滚动的速度,1ms往左移动1px
let myTimer = null
function scrollDiv(ele) {
let container = document.getElementById(ele) // 获取元素
container.innerHTML = container.innerHTML + container.innerHTML + container.innerHTML + container.innerHTML
// 多复制几份为了防止出现尾部空白和断层,可以根据div中总元素宽度调整复制几份
let childDivList = container.children
// 监听每个子元素的鼠标移入、移出
for (let childDiv of childDivList) {
childDiv.onmouseover = function () {
clearTimeout(myTimer) //移入终止执行moveDiv函数
}
childDiv.onmouseout = function () {
moveDiv(ele) //移出则重新执行moveDiv函数
}
}
moveDiv(ele)
}
function moveDiv (ele) {
let container = document.getElementById(ele)
container.scrollLeft++
if (container.scrollLeft >= container.scrollWidth / 4) {
container.scrollLeft = 0 //当元素移动从第一个红色div到第一个黑色div时,恢复初始位置,进行轮循
}
myTimer = setTimeout("moveDiv('" + ele + "')", delayTime) // delayTime = 1ms之后,重新执行moveDiv函数
}
window.onload = function () {
scrollDiv("carousel-container");
}
</script>
</head>
<body>
<div id="carousel-container" >
<div class="first_red"></div>
<div class="second_orange"></div>
<div class="third_yellow"></div>
<div class="four_green"></div>
<div class="five_blue"></div>
<div class="six_indigo"></div>
<div class="seven_violet"></div>
<div class="eight_white"></div>
<div class="nine_black"></div>
</div>
</body>
</html>
js走马灯,完整代码
于 2024-06-03 20:03:03 首次发布