how to get right offset of an element? - jQuery

2019-01-16 09:26发布

This is probably a really simple question, but how do I go about getting the right offset of an element in jQuery?

I can do:

$("#whatever").offset().left;

and it is valid.

But it seems that:

$("#whatever").offset().right 

is undefined.

So how does one accomplish this in jQuery?

Thanks!!

标签: jquery offset
8条回答
Root(大扎)
2楼-- · 2019-01-16 10:09

There's a native DOM API that achieves this out of the box — getBoundingClientRect:

document.querySelector("#whatever").getBoundingClientRect().right
查看更多
等我变得足够好
3楼-- · 2019-01-16 10:10

Getting the anchor point of a div/table (left) = $("#whatever").offset().left; - ok!

Getting the anchor point of a div/table (right) you can use the code below.

 $("#whatever").width();
查看更多
孤傲高冷的网名
4楼-- · 2019-01-16 10:13

Alex, Gary:

As requested, here is my comment posted as an answer:

var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

Thanks for letting me know.

In pseudo code that can be expressed as:

The right offset is:

The window's width MINUS
( The element's left offset PLUS the element's outer width )

查看更多
Explosion°爆炸
5楼-- · 2019-01-16 10:16

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));
查看更多
淡お忘
6楼-- · 2019-01-16 10:18
var $whatever        = $('#whatever');
var ending_right     = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

Reference: .outerWidth()

查看更多
看我几分像从前
7楼-- · 2019-01-16 10:18

Maybe I'm misunderstanding your question, but the offset is supposed to give you two variables: a horizontal and a vertical. This defines the position of the element. So what you're looking for is:

$("#whatever").offset().left

and

$("#whatever").offset().top

If you need to know where the right boundary of your element is, then you should use:

$("#whatever").offset().left + $("#whatever").outerWidth()
查看更多
登录 后发表回答