使用Chrome获取Javascript中对象的真实位置 [英] Get real position of objects in Javascript with Chrome
问题描述
我一直在编写一段Javascript代码,随机地在这个页面上放置一个ducky。
我想让它隐藏在对象的一面(比如帖子),但是我最终不得不硬编码它,因为我无法获取一种正确检索Chrome相关对象的真实位置的方法。我读了很多关于它的东西,并使用了递归的offsetParent方式,但没有得到任何好的结果。
我试过的最后一段代码是这样的:
var getPost = function(obj){
var pos = {'x':0,'y': 0};
if(obj.offsetParent){
while(1){
pos.x + = obj.offsetLeft;
pos.y + = obj.offsetTop;
if(!obj.offsetParent){
break;
}
obj = obj.offsetParent;
}
} else if(obj.x){
pos.x + = obj.x;
pos.y + = obj.y;
}
返回pos;
}
此代码不适用于Chrome,除了绝对位置(用CSS设置)。
是否有一个很好的跨浏览器的方式来实现这一目标?
好的,我的问题在其他地方。这是我正在做的调用函数:
var allPosts = document.getElementsByClassName('post-outer');
(post in allPosts){
console.log('Post has position'+ getPos(post));
$ b 你可以告诉我不习惯Javascript中的递归行为for循环,所以下面的代码实际上修复了我的问题:
var allPosts = document.getElementsByClassName('post-outer');
for(var i = 0,len = allPosts.length; i< len; ++ i){
console.log('Post position is'+ getPos(allPosts [i] ).Y);
}
感谢您的帮助: - )
I've been coding a bit of Javascript to place a ducky randomly on this page.
I wanted to make it hide on the side of objects (like the posts), but I ended up having to hardcode quite a bit of it, since I couldn't get a way to properly retrieve the real position of relative objects with Chrome. I read quite a few things about it, and used the recursive offsetParent way, but didn't get any good results.
The last bit of code I tried was this:
var getPost = function (obj) {
var pos = {'x':0,'y':0};
if(obj.offsetParent) {
while(1) {
pos.x += obj.offsetLeft;
pos.y += obj.offsetTop;
if(!obj.offsetParent) {
break;
}
obj = obj.offsetParent;
}
} else if(obj.x) {
pos.x += obj.x;
pos.y += obj.y;
}
return pos;
}
This code doesn't work on Chrome, except on objects with an absolute position (set with CSS).
Is there a good, cross-browser way to achieve this?
解决方案 Alright, my problem was somewhere else. This is what I was doing to call the function:
var allPosts = document.getElementsByClassName('post-outer');
for (post in allPosts) {
console.log('Post has position '+getPos(post));
}
You can tell I'm not so used to Javascript's recursive behavior in the for loop, so the following code actually fixes my issue:
var allPosts = document.getElementsByClassName('post-outer');
for (var i=0, len=allPosts.length; i<len; ++i ){
console.log('Post position is '+getPos(allPosts[i]).y);
}
Thanks all for your help :-)
这篇关于使用Chrome获取Javascript中对象的真实位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!