动画演示
左右移动的文字
实现原理
通过JavaScript控制元素的CSS属性(如margin-left或transform),结合定时器(setInterval)实现连续的位置变化,从而产生文字左右移动的视觉效果。
完整代码示例
<!DOCTYPE html>
<html>
<head>
<style>
.moving-text {
display: inline-block;
/* 其他样式 */
}
</style>
</head>
<body>
<div id="textContainer" class="moving-text">左右移动的文字</div>
<script>
let position = 0;
let direction = 1; // 1表示向右,-1表示向左
let animationId;
function moveText() {
const container = document.getElementById('textContainer');
position += direction * 2;
// 边界检测
if (position > 200) direction = -1;
if (position < 0) direction = 1;
container.style.transform = `translateX(${position}px)`;
}
function startAnimation() {
if (!animationId) {
animationId = setInterval(moveText, 50);
}
}
function stopAnimation() {
if (animationId) {
clearInterval(animationId);
animationId = null;
}
}
function resetAnimation() {
stopAnimation();
document.getElementById('textContainer').style.transform = 'translateX(0)';
position = 0;
direction = 1;
}
</script>
</body>
</html>