Подтвердить что ты не робот

Получить нижнее и правое положение элемента

Я пытаюсь получить положение элемента внутри окна следующим образом:

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;

Однако внизу и справа есть - перед ними... Почему это? поскольку числа правильны, они НЕ должны быть минус.

4b9b3361

Ответ 1

Вместо

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;

Ответ 2

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();

Ответ 3

// 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');

Это позволит найти расстояние от верха и слева от вашего видового экрана до вашего точного края элемента и ничего кроме этого. Так что скажем, что ваш логотип был 350px, и у него был левый край 50px, переменная "right" будет содержать значение 400, потому что фактическое расстояние в пикселях, необходимое для перехода к краю вашего элемента, независимо от того, есть ли у вас больше отступов или поля справа от него.

Если ваш размер CSS для CSS-размера установлен в рамку-рамку, он будет продолжать работать так же, как если бы он был установлен как содержимое по умолчанию.

Ответ 4

Вы можете использовать . 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();

Ответ 5

Я думаю,

<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 bottom
    var rightFromRight = $(document).width() - right;
    // distance from document 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

в моем браузере Chrome.

Когда документ прокручивается, $(window).height() возвращает высоту окна просмотра браузера, а не ширину документа, из которого некоторые части скрыты в прокрутке. См. http://api.jquery.com/height/.