8

I'm trying to do a simple drag script. The idea is to save the position when the mouse is down, update the view while the mouse is moving, and stop when mouse is up. Problem, mouseup event isn't working properly.

See the code:

var target = $('a')
var pos = 0;
var dragging = false;

$(document).mousedown(function(e) { pos=e.pageX; dragging = true })
$(document).mouseup(function() { dragging = false })
$(document).mousemove(function(e) {
    if(dragging){ 
        target.css('left', e.pageX-pos);
    }
})  ​

Why mouseup works with a "a" tag: http://jsfiddle.net/leyou/c3TrG/1/

And why mouseup doesn't work with a "img" tag: http://jsfiddle.net/leyou/eNwzv/

Just try to drag them horizontally.

Same probleme on ie9, ff and chrome. Windows7

4

1 回答 1

27

只需添加e.preventDefault()到您的 mousedown 处理程序,如下所示:

var target = $('img')
var pos = 0;
var dragging = false;

$(document).mousedown(function(e) { e.preventDefault(); pos=e.pageX; dragging = true })
$(document).mouseup(function() { dragging = false })
$(document).mousemove(function(e) {
    if(dragging){ 
        target.css('left', e.pageX-pos);
    }
})

请参阅工作演示

修复的基本原理是,浏览器也在进行自己的本地图像拖放(例如,当您将图像拖出浏览器以将其拖放到外部应用程序中时),因此您需要取消该默认值使用.preventDefault().

于 2012-11-05T16:58:59.223 回答