Home > Article > Web Front-end > JavaScript enhancement tutorial - DOM programming (two methods of controlling div movement)
The first button control
First create two html buttons and a div and give the div a style
input type="button" value="左" id="1"> <input type="button" value="右" id="2"> <div id="3"> div { width: 100px; height: 100px; background-color: bisque; position: absolute; left: 100px; top: 100px; }
Then get the div and two buttons in the 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 the 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"; }Source code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: bisque; position: absolute; left: 100px; top: 100px; } </style> </head> <body> <input type="button" value="左" id="1"> <input type="button" value="右" id="2"> <div id="3"> </div> <script> var left = document.getElementById("2"); var right = document.getElementById("1"); var div = document.getElementById("3"); var x = 100; left.onclick = function () { x=x+10; div.style.left = x+"px"; } right.onclick = function () { x=x-10; div.style.left = x+"px"; } </script> </body> </html>
<div id="3"> </div> <style> div { width: 100px; height: 100px; background-color: bisque; position: absolute; left: 100px; top: 100px; } </style>
Get the div in the script
var div=document.getElementById("3");
Then declare two variables to control changing the left and top of the div
var px=100; var py =100;
Then get the key value
document.onkeydown (in the document document object, pressing any key will trigger this function)## The event.keyCode output in #alert will correspond to the event value corresponding to the current key when the key is pressed (that is, each key corresponds to a key value)
document.onkeydown = function(){ alert(event.keyCode); }
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; }Source code:
Title <script> var div=document.getElementById("3"); var px=100; var py =100; document.onkeydown = function(){ // alert(event.keyCode); 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; } } </script>