原生javascript实现的一个简单动画效果
本文章向大家介绍一个javascript实现的动画。点击开始按钮div会往右移动,点击停止后,div停止移动,再点击则继续移动。请看下面代码。
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<head>
<title>javascript实现的简单动画</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="开始运动" />
<input type="button" id="stopmove" value="停止运动" />
<div id="mydiv"></div>
</body>
</html>代码解释:
1.window.onload=function(){},当文档内容完全加载完毕再去执行函数中的代码。
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",设置div的left属性值。
6.start.onclick=function(){},为start元素注册onclick事件处理函数。
7.clearInterval(flag),停止定时器函数,一方多次单击开始按钮造成叠加效果。
8.flag=setInterval(move,20),开始运动。
相关推荐
zrtlin 2020-11-09
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17