你可以利用 JavaScript 創(chuàng)造一些復(fù)雜的運(yùn)動(dòng),包括下面但不限于下面的:
這個(gè)教程將講解如何利用 JavaScript 創(chuàng)建一些基本的運(yùn)動(dòng)。
JavaScript 可以用來(lái)移動(dòng)一些文檔對(duì)象模型元素(<img>
, <div>
或者其他的 HTML 元素)在頁(yè)面附近,這個(gè)是通過(guò)一些邏輯等式或者函數(shù)來(lái)決定的。
JavaScript 提供如下的幾種比較常用的函數(shù)來(lái)進(jìn)行動(dòng)畫(huà)編程。
JavaScript 能夠設(shè)置一系列文檔模型對(duì)象的屬性值,包括該對(duì)象在屏幕中的位置。你可以通過(guò)設(shè)置 top 和 left 等對(duì)象的屬性值,從而讓該對(duì)象放在屏幕中任何位置。如下是該語(yǔ)法的一個(gè)簡(jiǎn)單例子:
// 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;
讓我們利用文檔對(duì)象模型的對(duì)象的屬性值實(shí)現(xiàn)一個(gè)簡(jiǎn)單的動(dòng)畫(huà),JavaScript 的函數(shù)如下:
<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="/attachments/image/wk/wkjavascript/html.gif" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>
如下是對(duì)上面例子的解釋?zhuān)?/p>
在上面的例子中我們已經(jīng)看到如何讓一張圖片在每次點(diǎn)擊之后向右移動(dòng)。我們可以通過(guò)利用 JavaScript 中的函數(shù) setTimeout() 讓它自動(dòng)執(zhí)行這個(gè)操作:
<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="/attachments/image/wk/wkjavascript/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>
這里我們?cè)黾恿艘恍┬碌闹R(shí):
如下是一個(gè)簡(jiǎn)單的例子演示由鼠標(biāo)事件引起的圖片翻轉(zhuǎn):
<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="/attachments/image/wk/wkjavascript/html.gif" />
</a>
</body>
</html>
讓我們來(lái)看看這里的不同點(diǎn):
更多建議: