我很抱歉发布了这么多问题 - 我还在学习!所以,我可以毫无问题地拖放 html 中的第一个元素;但是,当我尝试拖放第二个时,它似乎相当在鼠标下方。无论我将鼠标移到哪里,它仍然会拖曳,但远在下方。怎么了?
这是javascript:
// JavaScript Document
var posX;
var posY;
var element;
document.addEventListener("mousedown", drag, false);
function drag(event) {
if(event.target.className == "square") {
element = event.target;
posX = event.clientX -parseInt(element.offsetLeft);
posY = event.clientY -parseInt(element.offsetTop);
document.addEventListener("mousemove", move, false);
}
}
function move(event) {
if (typeof(element.mouseup) == "undefined")
document.addEventListener("mouseup", drop, false);
//Prevents redundantly adding the same event handler repeatedly
element.style.left = event.clientX - posX + "px";
element.style.top = event.clientY - posY + "px";
}
function drop() {
document.removeEventListener("mousemove", move, false);
document.removeEventListener("mouseup", drop, false);
//alert("DEBUG_DROP");
}
这是 html:
<body>
<p class="square">Thing One</p>
<p class="square">Thing Two</p>
</body>
这是CSS:
/* CSS Document */
.square {
position: relative;
width: 100px;
height: 100px;
background: red;
}
p {
padding: 0px;
margin: 0px;
}
谢谢大家的宝贵时间!非常感谢!
最佳答案
这里有两个不同的问题需要考虑:
- 如何获取元素在页面上的位置?
- 当我为
left
分配新值时会发生什么和top
样式属性?
第一个问题的答案依赖于对 element.offsetLeft
的理解和 element.offsetTop
.这些属性给出了相对于 element.offsetParent
的偏移量这是 defined as “位置最近的(在包含层次结构中最近的)包含元素”。
在您的文档中,这是 <body>
元素,因此它按预期工作。如果您将方 block 放在其他元素中,您会发现您的代码将停止工作。你需要的是一个函数来遍历包含元素的树并对每个偏移量求和,like this :
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
}
这样使用:
var pos= findPos(element);
posX = event.clientX - pos.x;
posY = event.clientY - pos.y;
回答第二个问题需要了解相对定位的元素。相对定位的元素出现在相对于它们通常出现在页面上的位置相对的位置。当您为 top
赋值时和 left
你没有给出绝对值。您提供的位置被视为相对于元素在布局中的原始位置。这是相对定位的特性,而不是错误。您可能想使用 position: absolute;
相反。
关于javascript - 在 JavaScript 中实现相对定位元素的拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111492/