my javascript drag and drop engine (still working on it) doesn't work on the second drag if there is text involved. It still behaves normally except if you click the <p id="square" onmousedown="drag(event)">meep</p>
, the text drops down and follows you from not where you clicked- but from just below (a few cm) where you clicked. On the other hand, if I use a <div>
with no text, it works perfectly.
// JavaScript Document
var posX;
var posY;
var element;
function drag(event) {
element = document.getElementById("square");
posX = event.clientX -parseInt(element.offsetLeft);
posY = event.clientY -parseInt(element.offsetTop);
document.addEventListener("mousemove", move, false);
}
function move(event) {
if (typeof(document.getElementById("square").mouseup) == "undefined")
element.addEventListener("mouseup", 开发者_如何学Pythondrop, 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);
element.removeEventListener("mouseup", drop, false);
}
And the html is either:
<div id="square" onmousedown="drag(event)"></div>
or
<p id="square" onmousedown="drag(event)">meep</p>
and some css to save time:
#square {
position: relative;
width: 100px;
height: 100px;
background: red;
}
Thank you all for your answers and your time!
EDIT: A <div>
seems to work perfectly with text in it, but not a <p>
does your <p>
element have margin or padding? I'm guessing that's what pushes it out of place
精彩评论