問題描述
我一直在嘗試制作一個 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;
這篇關于獲取 div 元素的 X 和 Y 坐標的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!