JS實現(xiàn)元素上下左右移動效果
來源:懂視網(wǎng)
責(zé)編:小OO
時間:2020-11-27 22:27:35
JS實現(xiàn)元素上下左右移動效果
本文實例為大家分享了JS實現(xiàn)元素上下左右移動的具體代碼,供大家參考,具體內(nèi)容如下:<;<。DOCTYPE html>;<;html lang="en">;<;head>;<;meta charset="UTF-8">;<;title>;Document<;/title>;<;style>;a {cursor: pointer;}#cell {width: 30px;height: 30px;background: red;position: relative;left: 0;top: 0;}<;/style>;<;/head>;<;body onload="move()">;<;p>。
導(dǎo)讀本文實例為大家分享了JS實現(xiàn)元素上下左右移動的具體代碼,供大家參考,具體內(nèi)容如下:<;<。DOCTYPE html>;<;html lang="en">;<;head>;<;meta charset="UTF-8">;<;title>;Document<;/title>;<;style>;a {cursor: pointer;}#cell {width: 30px;height: 30px;background: red;position: relative;left: 0;top: 0;}<;/style>;<;/head>;<;body onload="move()">;<;p>。

本文實例為大家分享了JS實現(xiàn)元素上下左右移動的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
a {
cursor: pointer;
}
#cell {
width: 30px;
height: 30px;
background: red;
position: relative;
left: 0;
top: 0;
}
</style>
</head>
<body onload="move()">
<p>友情提示:請按鍵盤上的上下左右鍵</p>
<div id="cell"></div>
<script>
function move() {
var a = document.getElementById("cell");
a.style.left = 0;
a.style.top = 0;
document.onkeydown = function(e) {
var e = window.event ? window.event : e;
if(e.keyCode == 38) { //up
a.style.top = parseInt(a.style.top) - 50 + 'px';
//注意要用parseInt 因為a.style.top類型是字符串
}
if(e.keyCode == 40) { //down
a.style.top = parseInt(a.style.top) + 50 + 'px';
}
if(e.keyCode == 37) { //left
a.style.left = parseInt(a.style.left) - 50 + 'px';
}
if(e.keyCode == 39) { //right
a.style.left = parseInt(a.style.left) + 50 + 'px';
}
}
}
</script>
</body>
</html>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
JS實現(xiàn)元素上下左右移動效果
本文實例為大家分享了JS實現(xiàn)元素上下左右移動的具體代碼,供大家參考,具體內(nèi)容如下:<;<。DOCTYPE html>;<;html lang="en">;<;head>;<;meta charset="UTF-8">;<;title>;Document<;/title>;<;style>;a {cursor: pointer;}#cell {width: 30px;height: 30px;background: red;position: relative;left: 0;top: 0;}<;/style>;<;/head>;<;body onload="move()">;<;p>。