第一種按鈕控制
先建立兩個html按鈕和一個div並給div一個樣式
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; }
然後在script中獲得div和兩個按鈕
var left = document.getElementById("2"); var right = document.getElementById("1"); var div = document.getElementById("3");
然後添加onclick函數
left.onclick = function () { } right.onclick = function () { }設定一個變數,設定一個變數控制div的left改變
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"; }源碼:
<!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>
var div=document.getElementById("3");
然後獲得鍵值
document.onkeydown(在document文件物件中,按任何鍵都會觸發此函數)alert中輸出的event.keyCode會對應按鍵時,當前鍵對應的事件值(即每一個按鍵對應為一個鍵值)
var px=100; var py =100;
然後通過測試上下左右得到鍵值,在swich語句中改變div的left和top改變其位置
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; }