jQuery offset top doesn't work correctly

落花浮王杯 提交于 2019-11-27 14:44:51

问题


I'm trying to create an script draw something in an element by mouse and I'm using Raphaeljs to do that.

For correct drawing I need to find top and left of ‍input‍‍ element. I'm using var offset = $("#input").offset(); to get left and top.

But the top value isn't correct. It's 10px lower than ‍‍the real top distance. I think the 10px maybe change in different resolutions then I can't add 10px to it normally then I want to know how can I fix the problem!

I uploaded my test here.


回答1:


The jQuery .offset() function has this limitation:

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

The body in this case has a 10px top border, which is why your drawing is off by 10 pixels.

Recommended solution:

var offset = $("#input").offset();
x = x - offset.left - $(document.body).css( "border-left" );
y = y - offset.top + $(document.body).css( "border-top" );



回答2:


After fighting with this for a while and reviewing various potential answers I have concluded that jQuery offset().top (and presumably DOM API that it uses) is too unreliable for general use. Not only is it documented as excluding html level margins, but it also returns unexpected results in several other cases.

position().top does work, but it may not be practical / possible to design the page so that it is equivalent.

Fortunately I have found that element.getBoundingClientRect().top gets the position relative to the viewport perfectly. You can then add on $(document).scrollTop() to get the position from the top of the document if required.




回答3:


I have two different solutions:

1) You can calculate above element's total height with outerHeight(true) method. This method will calculate height with margins, paddings and borders.

And this won't create conflict, it will return true value. Here is jsFiddle example.

html

<div class="header"></div>
<div class="nav"></div>
<div class="myEle"></div>

jQuery

var myEleTop = $('.header').outerHeight(true) + $('.nav').outerHeight(true);

2) If you defined top css to the element which is postioned relative to the body, you can use this value too:

parseInt($('#myEle').css('top'));


来源:https://stackoverflow.com/questions/12087670/jquery-offset-top-doesnt-work-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!