Get div position (top) in javascript?

2020-06-18 01:18发布

One div i set the height in css using top:-26px;. I have other divs other places where i'd like to align with that div. I notice in jquery writing .css('top') gets me my css and not the y coord of the div. How do i get the absolute x,y position using javascript?

7条回答
叛逆
2楼-- · 2020-06-18 01:36

Use jQuery(element).offset()

Hope it helps.

For example

var elementPosition = jQuery(element).offset();
var elementTopPositon = elementPosition.top;
查看更多
【Aperson】
3楼-- · 2020-06-18 01:38
var MyElement = document.getElementById("...Your_DIV_Control...");

var top = MyElement.getBoundingClientRect().top;
查看更多
虎瘦雄心在
4楼-- · 2020-06-18 01:43

Try this code:

function getElementPosition(id) {
    var offsetTrail = document.getElementById(id);
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }

    return {
        left: offsetLeft,
        top: offsetTop
    };
}​

It will return an object with left and top variables.

If you use JQuery try offset() method:

var pos = $("#element").offset();
console.log(pos.left)
console.log(pos.top)
查看更多
孤傲高冷的网名
5楼-- · 2020-06-18 01:54

Cross browser safe down to IE 8, possibly even 7 or 6:

function offset(el) {
    var rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}
var offsetEl = offset(document.getElementById('some_id'));
console.log(offsetEl.left, offsetEl.top);

Short and fast and no jQuery needed.

查看更多
叛逆
6楼-- · 2020-06-18 01:55

You can use jQuery(element).offset().top

Hope it helps.

查看更多
狗以群分
7楼-- · 2020-06-18 01:56

I will give you the vanilla solution.. don't complain.. add a [0] to your element and it's fixed! :P hope this helps.

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById('yourElId') ).left; 
查看更多
登录 后发表回答