Home >Web Front-end >JS Tutorial >A simple animation effect implemented in native javascript_javascript skills

A simple animation effect implemented in native javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:07:211953browse

This article introduces you to an animation implemented in javascript. When you click the start button, the div will move to the right. When you click stop, the div will stop moving. If you click again, it will continue to move. Please see the code below.

<!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>

Code explanation:


1.window.onload=function(){}, when the document content is completely loaded, execute the code in the function.
2.var mydiv=document.getElementById("mydiv"), get the element whose id attribute value is mydiv.
3.var start=document.getElementById("start"), get the element whose id attribute hi is start.
4.var stopmove=document.getElementById("stopmove"), get the element whose id attribute value is stopmove.
5.mydiv.style.left=x+"px", set the left attribute value of div.
6.start.onclick=function(){}, register the onclick event processing function for the start element.
7.clearInterval(flag), stops the timer function, and one party clicks the start button multiple times to cause an overlay effect.
8.flag=setInterval(move,20), start moving.

The above simple animation effect implemented by native javascript is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn