如何区分JavaScript中的手动动画和自动动画?
手动动画
在“手动动画”下,动画过程不是自动的。以下是使用DOM对象属性和JavaScript函数的简单动画的实现,如下所示。以下列表包含不同的DOM方法。
我们正在使用JavaScript函数getElementById()获取DOM对象,然后将其分配给全局变量imgObj。
我们定义了一个初始化函数 init()来初始化 imgObj,并在其中设置其position和left属性。
在窗口加载时,我们正在调用初始化函数。
最后,我们调用moveRight() 函数将左距离增加10个像素。您也可以将其设置为负值以将其移到左侧。
示例
您可以尝试运行以下代码以在JavaScript中实现动画,
<html>
<head>
<title>JavaScript Animation</title>
<script>
<!--
var imgObj = null;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type = "button" value = "Click Me" onclick = "moveRight();" />
</form>
</body>
</html>自动化动画
我们可以通过使用JavaScript函数setTimeout()来自动执行此过程,如下所示:
在这里,我们添加了更多方法。所以让我们看看这里有什么新东西-
MoveRight的()函数是调用的setTimeout()函数来设置的位置imgObj。
我们添加了一个新函数stop()来清除由 setTimeout() 函数设置的计时器,并将该对象设置在其初始位置。
示例
您可以尝试运行以下代码以在JavaScript中实现自动动画-
<html>
<head>
<title>JavaScript Animation</title>
<script>
<!--
var imgObj = null;
var animate ;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type = "button" value = "Start" onclick = "moveRight();" />
<input type = "button" value = "Stop" onclick = "stop();" />
</form>
</body>
</html>