注意三點:
?1:事件名稱onkeydown。
?2:事件加給document,而非window。
?3: 把元素的top,left值分別用offsetTop,offsetLeft來設定。
?
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>鍵盤移動</title><style type="text/css">*{margin: 0;padding: 0;}h3{position: absolute;width: 200px;background: cadetblue;color: #fff;padding: 20px;}</style></head><body><h3 id="h3">注意三點:<br />1:事件名稱onkeydown<br />2:事件加給document,而非window。<br />3: 把元素的top,left值分別用offsetTop,offsetLeft來設定</h3></body>
js效果:【這里用了switch語句來進行判斷】
<script type="text/javascript">window.onload = function(){var oH3 = document.getElementById("h3");document.onkeydown = function(ev){var ev = ev || window.event;switch(ev.keyCode){case 37:case 100:oH3.style.left = oH3.offsetLeft - 10 + "px";break;case 38:case 104:oH3.style.top = oH3.offsetTop - 10 + "px";break;case 39:case 102:oH3.style.left = oH3.offsetLeft + 10 + "px";break;case 40:case 98:oH3.style.top = oH3.offsetTop + 10 + "px";break;default:console.log("請按上下左右鍵");break;}console.log(oH3.offsetTop+"+"+oH3.style.top);console.log(ev.keyCode);}}</script>
鍵值 keyCode說明:
數字小鍵盤中對應的上下左右: