Aar*_*ers 7 html javascript dom
最近在comp.lang.javascript中有一个线程,其中宣布了胜利但没有发布代码:
在HTML页面上,如何在浏览器和页面样式中可靠地找到元素(图像或按钮)的左下角坐标?在某些情况下,在"Ajax in Action"中提倡的方法(我有副本)似乎在IE中不起作用.为了使问题更容易,我们假设我们可以将全局文档样式设置为"传统"或"过渡"或其他.
请提供代码或指向代码的指针(一个适用于所有浏览器的完整功能) - 不要只是说"那很容易"而且只关注遍历DOM的内容 - 如果我想读那种东西我'我会回到comp.lang.javascript.如果这是重复,请骂我,并指出我的解决方案 - 我确实试图找到它.
根据我的经验,让这样的东西工作的唯一可靠方法是使用JQuery(不要害怕,它只是一个你必须包含的外部脚本文件).然后你可以使用像这样的语句
$('#element').position()
Run Code Online (Sandbox Code Playgroud)
要么
$('#element').offset()
Run Code Online (Sandbox Code Playgroud)
获取当前坐标,这在我迄今遇到的任何和所有浏览器中都能很好地工作.
我从网上找到了这个解决方案......这完全解决了我的问题。请检查此链接以获取来源。 http://www.quirksmode.org/js/findpos.html
/** This script finds the real position,
* so if you resize the page and run the script again,
* it points to the correct new position of the element.
*/
function findPos(obj){
var curleft = 0;
var curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return {X:curleft,Y:curtop};
}
}
Run Code Online (Sandbox Code Playgroud)
在 Firefox、IE8、Opera 中完美运行(也希望在其他人中)感谢那些分享他们知识的人......问候,
动态麦克风