获取一个div元素的X和Y坐标 [英] getting the X and Y coordinates for a div element
问题描述
我一直在尝试使一个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
事件处理程序和一段时间来继续移动元素,但是,任何提示/提示都非常感谢我最关心的是如何在循环中获得
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;
这篇关于获取一个div元素的X和Y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!