获取 div 元素的 X 和 Y 坐标

2022-01-11 00:00:00 drag-and-drop javascript

我一直在尝试制作一个 javascript 来获取 div 元素的 X 和 Y 坐标.经过一番尝试,我想出了一些数字,但我不确定如何验证它们的确切位置(脚本返回 X 为 168,Y 为 258)我正在运行屏幕分辨率为 1280 的脚本x 800.这是我用来获得此结果的脚本:

I've been trying to make a javascript to get a X and Y coordinates of a div element. After some trying around I have come up with some numbers but I'm not sure how to validate the exact location of them(the script returns the X as 168 and Y as 258) I'm running the script with a screen resolution of 1280 x 800. This is the script I use to get this result:

function get_x(div) {
    var getY;
    var element = document.getElementById("" + div).offsetHeight;
    var get_center_screen = screen.width / 2;

    document.getElementById("span_x").innerHTML = element;
    return getX;
}

function get_y(div) {
    var getY;
    var element = document.getElementById("" + div).offsetWidth;
    var get_center_screen = screen.height / 2;

    document.getElementById("span_y").innerHTML = element;
    return getY;
}​

现在的问题是.假设这些是函数返回的准确坐标是否合理,或者是否可以轻松地在该位置生成一些东西以查看它到底是什么?

Now the question is. Would it be reasonable to assume that these are accurate coordinates returned by the function or is there an easy to to just spawn a little something on that location to see what exactly it is?

最后我将如何让这个 div 元素移动?我知道我应该使用 mousedown 事件处理程序和一段时间来继续移动元素,但是非常感谢任何提示/提示我最关心的是如何让 while 循环运行.

And finally how would I go about making this div element move? I know I should use a mousedown event handler and a while to keep moving the element but yeah any tips/hints are greatly appreciated my biggest concern is to how to get that while loop running.

推荐答案

这里有一个简单的方法来获取关于 html 元素位置的各种信息:

Here a simple way to get various information regarding the position of a html element:

        var my_div = document.getElementById('my_div_id');
        var box = { left: 0, top: 0 };
        try {
            box = my_div.getBoundingClientRect();
        } 
        catch(e) 
        {}

        var doc = document,
            docElem = doc.documentElement,
            body = document.body,
            win = window,
            clientTop  = docElem.clientTop  || body.clientTop  || 0,
            clientLeft = docElem.clientLeft || body.clientLeft || 0,
            scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
            scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
            top  = box.top  + scrollTop  - clientTop,
            left = box.left + scrollLeft - clientLeft;

相关文章