开发者

How to avoid grabbing the image when using javascript drag n drop?

Here's my problem, it's long, but actually very simple, please at least skim it if you will.

I take a div called 'app' and drag it around the page. Works fine. Except occasionally when i grab the div and drag instead of dragging the div only an image of the div drags(in firefox & webkit browsers, not ie) and the mouse cursor turns into a circle with a line through it. This greatly compromises the interactivity of the webpage and i don't think its so much a coding issue as a browser issue.

I'll show the code used to drag below but first you should probably know that in order to drag I use three sets of variables, X1 & Y1 is the pageX and pageY (clientX or clientY depending on the browser) and or recorded every time the mouse moves.

X2 & Y2 are set when the mouse is pressed on the div, and are the difference between the mouse position and the current top & left position of the div, they are used so that when the div is dragged the mouse position isn't equal to the top left corner.

And finally dX and dY (short for delta X and delta Y) are the equal X1 - X2 and Y1 - Y2, they too are set when the mouse moves and equal the change in X and the change in Y.

Sorry for the explanation but i figured it might help clear up any confusions with the following code, here is the dragging code.

app.onmousedown = function() {

    X2 = app.offsetWidth - ((app.offsetWidth + app.offsetLeft) - X1);
    Y2 = app.offsetHeight - ((app.offsetHeight + app.offsetTop) - Y1);

main.onmousemove = function() {
    dX = X1 - X2;
    dY = Y1 - Y2;

    app.style.top = dY + 'px';
    app.style.left = dX + 'px';
}
}

Note the main div is simply a container holding all elements of the page, and is used for convenience because it equals the size of the web page.

And that's my issue really, as i said before it only occurs sometimes other times it works perfectly fine, without any errors. Yet it occurs often enough to be a problem. I know it's possible to get this working because i've seen drag and drop demos that don't suffer form this problem. So if anyone knows or has any ideas it'd be very much appreciated if not thanks anyway for bothering to read this i know it was long sorry for that.

ps: please don't suggest javascript frameworks instead, i'm not a fan of them. It's 开发者_运维知识库mearly a preference of mine i don't hate them i just prefer javascript.


try adding the attribute ondragstart="return false;" to the img tags, this should disable the browser built-in drag and drop funcitonality. You usually also need to do this for a tags

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜