学习使用 JavaScript 来创建 HTML 动画。
创建动画容器
所有动画都应该与容器元素关联。
<div id ="container">
<div id ="animate">我的动画在这里。</div>
</div>
为元素添加样式
应该通过 style = "position: relative" 创建容器元素。
应该通过 style = "position: absolute" 创建动画元素。
实例
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
然后
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
效果
也可以组合动画,比如边移动便改变他的大小。
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var width = 50;
var id = setInterval(frame, 2);
function frame() {
if (pos == 300) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
var id2 = setInterval(changeSize, 25);
function changeSize(){
if (width == 100){
clearInterval(id2)
}else{
width++
elem.style.width = width + 'px';
elem.style.height = width + 'px';
}
}
}
效果如下: