获取元素的底部和右侧位置

我试图在窗口中获取元素的位置,如下所示:

var link = $(element); var offset = link.offset(); var top = offset.top; var left = offset.left; var bottom = $(window).height() - link.height(); bottom = offset.top - bottom; var right = $(window).width() - link.width(); right = offset.left - right; 

然而,底部和右边-在他们面前…这是为什么? 因为数字是正确的,他们不应该减。

代替

 var bottom = $(window).height() - link.height(); bottom = offset.top - bottom; 

你为什么不这样做?

 var bottom = $(window).height() - top - link.height(); 

编辑:你的错误是你在做

 bottom = offset.top - bottom; 

代替

 bottom = bottom - offset.top; // or bottom -= offset.top; 
  var link = $(element);
 var offset = link.offset();

 var top = offset.top;
 var left = offset.left;

 var bottom = top + link.outerHeight();
 var right = left + link.outerWidth(); 
 // Returns bottom offset value + or - from viewport top function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom } // Returns right offset value function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right } var bottom = offsetBottom('#logo'); var right = offsetRight('#logo'); 

这将find从视口的顶部和左边到您的元素的确切边缘的距离,除此之外没有任何东西。 所以说你的logo是350px,它的左边距是50px,variables'right'将会保持一个400的值,因为这是以像素为单位到达元素边缘的实际距离,不pipe你是否有更多的填充或者右边的余量。

如果您的box-sizing CSS属性设置为边框,它将继续工作,就像它被设置为默认的内容框一样。

您可以使用.position()

 var link = $(element); var position = link.position(); //cache the position var right = $(window).width() - position.left - link.width(); var bottom = $(window).height() - position.top - link.height(); 

我认为

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div>Testing</div> <div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div> <div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div> <script> (function(){ var link=$("#result"); var top = link.offset().top; // position from $(document).offset().top var bottom = top + link.height(); // position from $(document).offset().top var left = link.offset().left; // position from $(document).offset().left var right = left + link.width(); // position from $(document).offset().left var bottomFromBottom = $(document).height() - bottom; // distance from document's bottom var rightFromRight = $(document).width() - right; // distance from document's right var str=""; str+="top: "+top+"<br>"; str+="bottom: "+bottom+"<br>"; str+="left: "+left+"<br>"; str+="right: "+right+"<br>"; str+="bottomFromBottom: "+bottomFromBottom+"<br>"; str+="rightFromRight: "+rightFromRight+"<br>"; link.html(str); })(); </script> 

结果是

 top: 44 bottom: 544 left: 72 right: 1277 bottomFromBottom: 3068 rightFromRight: 3731 

在我的铬浏览器。

当文档是可滚动的时, $(window).height()返回浏览器视口的高度,而不是滚动时某些部分隐藏的文档的宽度。 请参阅http://api.jquery.com/height/