Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 135.0MB ·虚拟内存 1372.6MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
我们可以使用JavaScript创建一个复杂的动画,其中包含但不限于以下元素:
在本章中,我们将看到如何使用JavaScript创建动画。
根据逻辑方程或函数确定的某种模式,可以使用JavaScript来移动页面周围的大量DOM元素(<img/>,<div>或任何其他HTML元素)。
JavaScript提供了以下功能,以便在动画程序中经常使用。
JavaScript还可以设置DOM对象的许多属性,包括其在屏幕上的位置。您可以设置对象的顶部和左侧属性,将其放置在屏幕的任何位置。以下是相同的语法。
// Set distance from left edge of the screen. object.style.left = distance in pixels or points; or // Set distance from top edge of the screen. object.style.top = distance in pixels or points;
所以让我们使用DOM对象属性和JavaScript函数来实现一个简单的动画,如下所示。以下列表包含不同的DOM方法。
实例
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
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()来自动执行此过程,如下所示。
这里我们添加了更多的方法。所以,让我们看看这里有什么新东西。
实例
<html>
<head>
<title>JavaScript Animation</title>
<script type = "text/javascript">
<!--
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>
这是一个简单的例子,展示了鼠标事件的图像翻转。让我们看看我们在下面的例子中使用什么 -
<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type = "text/javascript">
<!--
if(document.images) {
var image1 = new Image();
// Preload an image image1.src = "/images/html.gif";
var image2 = new Image();
// Preload second image image2.src = "/images/http.gif";
}
//
-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href = "#" onMouseOver = "document.myImage.src = image2.src;"
onMouseOut = "document.myImage.src = image1.src;">
<img name = "myImage" src = "/images/html.gif" />
</a>
</body>
</html>
JavaScript导航器对象包含一个名为plugins的子对象。该对象是一个数组,每个浏览器上安装的插件都有一个条目。navigator.plugins对象仅受Netscape,Firefox和Mozilla支持。以下示例 ...