本文章向大家介紹一個(gè)javascript實(shí)現(xiàn)的動(dòng)畫。點(diǎn)擊開始按鈕div會往右移動(dòng),點(diǎn)擊停止后,div停止移動(dòng),再點(diǎn)擊則繼續(xù)移動(dòng)。請看下面代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<head>
<title>javascript實(shí)現(xiàn)的簡單動(dòng)畫</title>
<style type="text/css">
#mydiv
{
width:50px;
height:50px;
background-color:green;
position:absolute;
}
</style>
<script type="text/javascript">
window.onload=function()
{
var mydiv=document.getElementById("mydiv");
var start=document.getElementById("start");
var stopmove=document.getElementById("stopmove");
var x=0;
var flag;
function move()
{
x=x+1;
mydiv.style.left=x+"px";
}
start.onclick=function()
{
clearInterval(flag);
flag=setInterval(move,20);
}
stopmove.onclick=function()
{
clearInterval(flag);
}
}
</script>
<body>
<input type="button" id="start" value="開始運(yùn)動(dòng)" />
<input type="button" id="stopmove" value="停止運(yùn)動(dòng)" />
<div id="mydiv"></div>
</body>
</html>
代碼解釋:
1.window.onload=function(){},當(dāng)文檔內(nèi)容完全加載完畢再去執(zhí)行函數(shù)中的代碼。
2.var mydiv=document.getElementById("mydiv"),獲取id屬性值為mydiv的元素。
3.var start=document.getElementById("start"),獲取id屬性hi為start的元素。
4.var stopmove=document.getElementById("stopmove"),獲取id屬性值為stopmove的元素。
5.mydiv.style.left=x+"px",設(shè)置div的left屬性值。
6.start.onclick=function(){},為start元素注冊onclick事件處理函數(shù)。
7.clearInterval(flag),停止定時(shí)器函數(shù),一方多次單擊開始按鈕造成疊加效果。
8.flag=setInterval(move,20),開始運(yùn)動(dòng)。
以上這篇原生javascript實(shí)現(xiàn)的一個(gè)簡單動(dòng)畫效果就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考