Javascript 鼠标相对于 div 的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3824332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:17:11  来源:igfitidea点击:

Mouse position relative to div

javascriptjquery

提问by Shishant

I am using jquery ui for drag and drop. I am trying to get mouse position relative to div, here is my code:

我正在使用 jquery ui 进行拖放。我正在尝试获取相对于 div 的鼠标位置,这是我的代码:

$( "#db_tables " ).droppable({
  activeClass: "ui-state-default",
  hoverClass: "ui-state-hover",
  drop: function( event, ui ) {
    var x = ui.position.left - ui.offset.left; // tired event.pageX - this.offsetLeft;
    var y = ui.position.top - ui.offset.top; // tired event.pageY - this.offsetTop;
    $( '<div style="margin-top:' + y   + 'px; margin-left:' + x   + 'px; "></div>' ).html( ui.draggable.html() ).appendTo( this );
  }
});

But the position of dropped div is not correct, Can anybody please tell me what is wrong with code?

但是下降的div的位置不正确,有人可以告诉我代码有什么问题吗?

回答by fehays

Take a look here:

看看这里:

http://docs.jquery.com/Tutorials:Mouse_Position

http://docs.jquery.com/Tutorials:Mouse_Position

EDIT: The jquery docs page above is broken. Here is an alternate:

编辑:上面的 jquery 文档页面已损坏。这是一个替代方案:

http://api.jquery.com/event.pageX/

http://api.jquery.com/event.pageX/

event.pageXand event.pageYshould give you mouse position

event.pageX并且event.pageY应该给你鼠标位置

$("#drag").draggable({
    stop: function(event, ui){
        var x = event.pageX - ui.offset.left;
        var y = event.pageY - ui.offset.top;       
    }
});

EDIT: here's an example showing how to track the mouse position relative to the element you are dragging http://jsfiddle.net/87fqr/1/

编辑:这是一个示例,显示如何跟踪相对于您正在拖动的元素的鼠标位置http://jsfiddle.net/87fqr/1/

ANOTHER EDIT:

另一个编辑:

This should work if you want the position of the mouse relative to the droppable:

如果您想要鼠标相对于放置项的位置,这应该有效:

$("#db_tables").droppable({
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function( event, ui ) {
            var offset = $(this).offset(),
            x = event.pageX - offset.left,
            y = event.pageY - offset.top; 
        $('<div style="margin-top:' + y + 'px; margin-left:' + x + 'px; "></div>' ).html( ui.draggable.html() ).appendTo( this );
    }
});

More complete example here: http://jsfiddle.net/87fqr/2/

更完整的例子在这里:http: //jsfiddle.net/87fqr/2/