在img上进行mousemove后,mouseup不起作用 [英] Mouseup not working after mousemove on img

查看:640
本文介绍了在img上进行mousemove后,mouseup不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的拖动脚本. 这个想法是在鼠标按下时保存位置,在鼠标移动时更新视图,在鼠标上升时停止.问题,mouseup事件无法正常工作.

查看代码:

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);
    }
})  ​

为什么mouseup使用"a"标签: http://jsfiddle.net/leyou/c3TrG/1/

以及为什么mouseup不能与"img"标记一起使用: http://jsfiddle.net/leyou/eNwzv/

只需尝试将其水平拖动即可.

ie9,ff和chrome出现相同问题. Windows7

解决方案

只需将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()取消默认的拖放操作./p>

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

解决方案

Just add e.preventDefault() to your mousedown handler, like this:

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);
    }
})

See working demo .

The rationale is the browser was also doing his own native image drag and drop (like to drag an image and drop it in an application outside the browser) so you need to cancel that default drag and drop with .preventDefault() .

这篇关于在img上进行mousemove后,mouseup不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆