歌者文明清理员 发表于 2023-8-16 11:35:18

html问题

<!DOCTYPE html>
<html>
<style>
#test {
position: absolute;
padding: 10px;
cursor: move;
z-index: 10;
}
</style>
<body>

<div id="test">test</div>

<script>
let elmnt = document.getElementById("test");
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = mousedown;
function mousedown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.screenX;
pos4 = e.screenY;
document.onmouseup = function(){
        document.onmousedown = null;
        document.onmousemove = null;
};
document.onmousemove = drag;
}
function drag(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.screenX;
pos4 = e.screenY;
elmnt.style.top = (pos3) + "px";
elmnt.style.left = (pos4) + "px";
}
</script>

</body>
</html>





啊啊啊到底是哪里错了{:10_266:}

isdkz 发表于 2023-8-16 11:35:39

在你的代码中,你想要通过鼠标拖拽来移动一个元素。然而,你的代码中有一个错误。在drag函数中,你应该将pos3赋给elmnt.style.left ,将pos4赋给elmnt.style.top ,而不是相反。

这是修正后的代码:

<!DOCTYPE html>
<html>
<style>
#test {
position: absolute;
padding: 10px;
cursor: move;
z-index: 10;
}
</style>
<body>

<div id="test">test</div>

<script>
let elmnt = document.getElementById("test");
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = mousedown;

function mousedown(e) {
e = e || window.event;
e.preventDefault();
pos3 = e.screenX;
pos4 = e.screenY;
document.onmouseup = function(){
       document.onmousedown = null;
       document.onmousemove = null;
};
document.onmousemove = drag;
}

function drag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.screenX;
pos2 = pos4 - e.screenY;
pos3 = e.screenX;
pos4 = e.screenY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
</script>

</body>
</html>


这样,你应该能够通过鼠标拖拽来移动元素了。

cjjJasonchen 发表于 2023-8-16 12:08:39

xy反了吧

歌者文明清理员 发表于 2023-8-16 12:11:00

cjjJasonchen 发表于 2023-8-16 12:08
xy反了吧

cjjJasonchen 发表于 2023-8-16 12:13:49

{:10_282:}我还没有学到这呢

琅琊王朝 发表于 2023-8-16 12:31:51

出现错误的原因是在drag函数中将pos3赋值给了elmnt.style.top,将pos4赋值给了elmnt.style.left,导致元素在移动时位置改变不正确。
你可以修改drag函数中的代码:
function drag(e) {
e = e || window.event;
e.preventDefault();
let newPos1 = e.screenX - pos3;
let newPos2 = e.screenY - pos4;
pos3 = e.screenX;
pos4 = e.screenY;
elmnt.style.top = (elmnt.offsetTop + newPos2) + "px";
elmnt.style.left = (elmnt.offsetLeft + newPos1) + "px";
}

Ewan-Ahiouy 发表于 2023-8-16 13:57:30

应该是x, y坐标反了
页: [1]
查看完整版本: html问题