JavaScript 动画是指使用 JavaScript 代码来控制网页元素的动态效果,使其在视觉上产生变化。这种技术可以让网页变得更加生动和吸引人。
基础概念:
setTimeout
和 setInterval
函数可以用来控制动画的执行时间和频率。优势:
类型:
应用场景:
遇到的问题及解决方法:
Promise
或者 async/await
来控制动画的执行顺序。示例代码(CSS 动画):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Animation Example</title>
<style>
.box {
width: 50px;
height: 50px;
background-color: red;
transition: transform 1s;
}
.move {
transform: translateX(200px);
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<button onclick="moveBox()">Move Box</button>
<script>
function moveBox() {
const box = document.getElementById('box');
box.classList.toggle('move');
}
</script>
</body>
</html>
在这个例子中,点击按钮会触发 moveBox
函数,该函数会切换 .box
元素的 move
类,从而触发 CSS 过渡效果,使盒子在水平方向上移动。
领取专属 10元无门槛券
手把手带您无忧上云