拖拽移动div
https://code.h5jun.com/fofev/edit?html,css,js,output
<div id="box"><style>*{margin: 0;padding: 0;}body{position: relative;}#box{width: 50px;height: 50px;background: deepskyblue;position: absolute;left: 100px;top: 50px;}</style>
const box = document.getElementById("box");let nowW, nowH, flag;box.onmousedown = function (e) {nowW = e.clientX;nowH = e.clientY;flag = true;document.onmousemove = function (e) {if (!flag) return false;const moveX = e.clientX - nowW;const moveY = e.clientY - nowH;const left = parseInt(box.style.left || 0);const top = parseInt(box.style.top || 0);box.style.left = left + moveX + "px";box.style.top = top + moveY + "px";nowW = e.clientX;nowH = e.clientY;};document.onmouseup = function () {flag = false;};document.onmouseleave = function () {flag = false;};};
键盘移动div
https://code.h5jun.com/kehum/edit?html,css,js,output
<body><div id="box"><div id="move">静止</div></div><script>const box = document.getElementById("box");const move = document.getElementById("move");let lefts = box.style.left || 0;let tops = box.style.top || 0;document.addEventListener("keydown", function (e) {const code = e.keyCode;move.innerHTML = "开始移动";switch (code) {case 38:move.innerHTML = "上";tops -= 5;break;case 40:move.innerHTML = "下";tops += 5;break;case 37:move.innerHTML = "左";lefts -= 5;break;case 39:move.innerHTML = "右";lefts += 5;break;default:break;}box.style.top = tops + "px";box.style.left = lefts + "px";});document.addEventListener("keyup", function () {move.innerHTML = "静止";});document.addEventListener("keypress", function () {console.log("keypress");});</script></body>
