<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#parentDiv {
width: 300px;
overflow: hidden;
white-space: nowrap;
}
#childContainer {
display: inline-block;
}
.childDiv {
width: 100px;
height: 100px;
background-color: #3498db;
margin-right: 10px;
display: inline-block;
}
</style>
</head>
<body>
<div id="parentDiv">
<div id="childContainer">
<div class="childDiv">1</div>
<div class="childDiv">2</div>
<div class="childDiv">3</div>
<div class="childDiv">4</div>
<div class="childDiv">5</div>
<!-- 添加更多子div根据需要 -->
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var parentDiv = document.getElementById('parentDiv');
var childContainer = document.getElementById('childContainer');
var childWidth = document.querySelector('.childDiv').offsetWidth;
var totalWidth = childWidth * document.querySelectorAll('.childDiv').length;
// 判断子div总宽度是否超过父div宽度
if (totalWidth > parentDiv.offsetWidth) {
// 设置子div容器宽度,确保子div在一行显示
childContainer.style.width = totalWidth + 'px';
// 将滚动的动画时长设置为总宽度除以100,确保速度适中
var animationDuration = totalWidth / 100;
document.styleSheets[0].insertRule('@keyframes scrollAnimation { 0% { transform: translateX(0); } 100% { transform: translateX(-' + totalWidth + 'px); } }', 0);
document.styleSheets[0].insertRule('#childContainer { animation: scrollAnimation ' + animationDuration + 's linear infinite; }', 1);
// 鼠标悬停和离开事件处理
parentDiv.addEventListener('mouseover', function () {
childContainer.style.animationPlayState = 'paused';
});
parentDiv.addEventListener('mouseout', function () {
childContainer.style.animationPlayState = 'running';
});
}
});
</script>
</body>
</html>