繁体   English   中英

获取鼠标在间隔内的位置以使用鼠标移动div

[英]get position of mouse inside interval to move a div with mouse

我正在尝试通过鼠标光标的移动来移动div,但无法理解如何在超时范围内获取新更新的鼠标位置。 也许有一种更简单的方法。

var t;
$(document).ready(function(){
    $("body").on("mousedown", ".heading", function (e) {
        $("body").data("header_click", true);

        if ($("body").data("header_click")) {

            var container = $("#dialog");

            container.css("position", "absolute");

            t = setInterval(function(){

                //some way to get mouse position
                var pos = container.position();

                container.css({

                    top: "",//set based on mouse position
                    left: "",//set based on mouse position

                });

            }, 100);    

        }else{
            document.clearInterval(t);
        }

    });
});

$("body").on("mousedown", ".heading", function (e) {
    $("body").data("header_click", false);
});

这里找到的解决方案对我不起作用。

您将需要绑定到鼠标移动事件并更新文档变量。

var currentMousePos = { x: -1, y: -1 };
$(document).on('mousemove', function(event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
});

然后使用相对于要拖动的元素的绝对位置的那些位置来计算和更新元素的新位置。

$(document).ready(function(){
    $("body").on("mousedown", ".heading", function (e) {
        $("body").data("header_click", true);
        if ($("body").data("header_click")) {
            var container = $("#dialog");
            container.css("position", "absolute");

            var containerPos = container.pos();
            var mouseTopOffset = containerPos.top - currentMousePos.y;
            var mouseLeftOffset = containerPos.left - currentMousePos.x;

            container.css("left", mouseTopOffset +"px");
            container.css("top", mouseLeftOffset +"px");
        }
    }
}

我还没有真正测试过,但理论上应该做您所需要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM