gpt4 book ai didi

Javascript 拖放代码适用于 div,但不适用于 img

转载 作者:行者123 更新时间:2023-11-28 09:31:27 25 4
gpt4 key购买 nike

我对 JavaScript 还很陌生,所以任何帮助都会很棒!

我创建了这个小代码块,让我可以抓取一个 div 并拖动它。我将“dragme”id 分配给 div,一切都很好。问题是,如果我从 html 中替换该 div 并放置一个 img 元素(显然将“dragme”id 分配给 img),则事情不会按预期工作。

当我单击并拖动 img 时,它实际上移动了大约 3 或 4 个像素,然后它卡住,直到我抬起鼠标按钮(鼠标向上)。

是否存在某些属性或特征会阻止 img 元素以与 div 相同的方式起作用?

var isClicked = false;
var startClientX = 0;
var startClientY = 0;
var startLeft = 0;
var startTop = 0;

window.addEventListener("load", addListeners, true);

function addListeners()
{
document.getElementById("dragme").addEventListener("mousedown", mouseIsDown, false);
document.getElementById("dragme").addEventListener("mouseup", mouseIsUp, false);
window.addEventListener("mousemove", moveImage, false);

function mouseIsDown(e)
{
if (isClicked == false)
{
isClicked = true;
startClientX = e.clientX;
startClientY = e.clientY;
startLeft = document.getElementById("dragme").offsetLeft;
startTop = document.getElementById("dragme").offsetTop;
}
}

function mouseIsUp()
{
if (isClicked == true)
{
isClicked = false;
}
}

function moveImage(e)
{
if (isClicked == true)
{
imageLeftDif = e.clientX - startClientX;
imageTopDif = e.clientY - startClientY;
var newLeftPos = (startLeft + imageLeftDif) + "px";
var newTopPos = (startTop + imageTopDif) + "px";

document.getElementById("dragme").style.left = newLeftPos;
document.getElementById("dragme").style.top = newTopPos;
}
}
}

最佳答案

这解决了问题(答案作为 syazdani 的评论提供):

I'd venture to say that the built in browser drag and drop for images is kicking in. Try e.preventDefault and return false in the mousedown handler. – syazdani Dec 2 '12 at 17:26

关于Javascript 拖放代码适用于 div,但不适用于 img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com