在JavaScript中实现左右连续滚动效果,通常涉及到定时器(如setInterval
)和DOM元素的操作。以下是相关基础概念及实现方式:
setInterval
函数可以按照指定的时间间隔重复执行一段代码。以下是一个简单的JavaScript左右连续滚动示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>左右连续滚动示例</title>
<style>
#scrollContainer {
width: 300px;
overflow: hidden;
white-space: nowrap;
border: 1px solid #ccc;
}
.scrollItem {
display: inline-block;
padding: 10px;
margin-right: 20px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="scrollContainer">
<div class="scrollItem">内容1</div>
<div class="scrollItem">内容2</div>
<div class="scrollItem">内容3</div>
<div class="scrollItem">内容4</div>
</div>
<script>
function startScrolling() {
const container = document.getElementById('scrollContainer');
let position = 0;
const speed = 2; // 滚动速度,数值越小滚动越慢
setInterval(() => {
position -= speed;
if (Math.abs(position) >= container.offsetWidth / 2) { // 当滚动到一半宽度时,重置位置
position = container.offsetWidth;
}
container.style.transform = `translateX(${position}px)`;
}, 20); // 定时器时间间隔,数值越小滚动越流畅
}
window.onload = startScrolling;
</script>
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云