This article ish5eduAgency officialHTML5 Trainingtutorials, the main introduction:JavaScript Intensive Tutorials--dom Programming (two ways to control div movement)
First KindButton Control
first create two HTML buttons and a div and give the div a style
input type= "button" value= "left" id= "1" ><input type= "button" value= "right" id= "2 "><div id=" 3 ";
div { width: 100px; height: 100px; background-color: bisque; position: absolute; left: 100px; top: 100px; }
Then get div and two buttons in script
var left = document.getElementById ("2"); var right = document.getElementById ("1"); var div = document.getElementById ("3");
Then add the onclick function
Left.onclick = function () {} Right.onclick = function () {}
Set a variable to control the left change of the Div
var x = 100;
Triggered when a button is clicked
Left.onclick = function () {x=x+10; Div.style.left = x+ "px"; } Right.onclick = function () {x=x-10; Div.style.left = x+ "px"; }
<! Doctype html>
The second Kind, key-value control
also create a div in HTML and give it a style
<div id= "3" ></div>
<style> div { width: 100px; height: 100px; Background-color: bisque; position : absolute; left: 100px; top: 100px; } </style>
Get Div in script
var Div=document.getelementbyid ("3");
Then declare two variables control to change the left and top of Div
var px=100; var py = 100;
then get the key value
Document.onkeydown (in the Document object, pressing any key will trigger this function)
The Event.keycode of the output in alert corresponds to the corresponding event value of the current key (that is, each key corresponds to a value) .
Document.onkeydown = function () {alert (event.keycode);}
Then we get the key value by the test, change the left and top of the div to change its position in the Swich statement.
switch (Event.keycode) { case 37: px = px-10; div.style.left = px+ "px"; break; case 38: py = py-10; div.style.top = py+ "px"; break; case 39: px = px+10; div.style.left = px+ "px"; break; case 40: py = py+10; div.style.top = py+ "px"; break; }
<! Doctype html>Click to enter JS Intensive tutorial
This article is from the "11721999" blog, please be sure to keep this source http://11731999.blog.51cto.com/11721999/1827680
JavaScript Intensive Tutorial--dom programming (two ways to control div movement)