本文主要为大家详细介绍了JS实现元素上下左右移动效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <!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>
<p id="cell"></p>
<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) {
a.style.top = parseInt(a.style.top) - 50 + 'px';
}
if (e.keyCode == 40) {
a.style.top = parseInt(a.style.top) + 50 + 'px';
}
if (e.keyCode == 37) {
a.style.left = parseInt(a.style.left) - 50 + 'px';
}
if (e.keyCode == 39) {
a.style.left = parseInt(a.style.left) + 50 + 'px';
}
}
}
</script>
</body>
</html>
|
登录后复制
相关推荐:
JavaScript Select和Option列表元素上下左右移动_表单特效
使用js获取伪元素的content实例分享
jQuery remove()过滤被删除的元素详解
以上是JS实现元素上下左右移动的详细内容。更多信息请关注PHP中文网其他相关文章!