Offset (). top vs. offset from the top of the window

So I am trying to do some calculations with javascript / jquery to make the elements in my web app responsive. I understand that by using object.offset().top

I can get the number of pixels between the top of my content and the top of the object. However, part of my design is that some of the elements dock to the top of the screen and the rest scrolls past and then object.offset().top

not used in the same way as it does.

What I would like to know: is there a method to determine the distance between my object and the top of the user's screen (as opposed to the object and the top of my content)? I am using the latest version of Chrome.

Greetings

+3


source to share


1 answer


is there a method to determine the distance between my object and the top of the user's screen.

Yes, there is - getBoundingClientRect :

"Value TextRectangle is an object that contains properties left

, top

, right

and bottom

read-only> describing the boundary box in pixels: upper and left relative to the upper level, at the left viewing window."



I did a (more than) crude example here, http://jsfiddle.net/7ceL8p3s/ - scroll through the red border in the view and click on it - this will register the object TextRectangle

to the console every time you click and you will see values top

and left

relative view windows. (In the jsfiddle viewport that is located, go to http://jsfiddle.net/7ceL8p3s/show/ to see it in full.)

And if you scroll it so that the window is not partially displayed on the top border of the viewport, so that only the bottom of it is visible, you will also get negative values top

. (The same should happen for left

if you have a layout where the element can scroll from view to the left.)

+1


source







All Articles