需要在javascript中计算offsetRight

Dan*_*iff 7 javascript offset

我需要计算DOM对象的offsetRight。我已经有一些相当简单的代码来获取offsetLeft,但是没有javascript offsetRight属性。如果我添加offsetLeft和offsetWidth,那行得通吗?或者,还有更好的方法?

function getOffsetLeft(obj)
{
    if(obj == null)
        return 0;
    var offsetLeft = 0;
    var tmp = obj;
    while(tmp != null)
    {
        offsetLeft += tmp.offsetLeft;
        tmp = tmp.offsetParent;
    }
    return offsetLeft;
}

function getOffsetRight(obj)
{
    if (obj == null)
        return 0;
    var offsetRight = 0;
    var tmp = obj;
    while (tmp != null)
    {
        offsetRight += tmp.offsetLeft + tmp.offsetWidth;
        tmp = tmp.offsetParent;
    }
    return offsetRight;    
}
Run Code Online (Sandbox Code Playgroud)

小智 8

不能比这更简单:

var offsetright = window.innerWidth - obj.offsetLeft - obj.offsetWidth
Run Code Online (Sandbox Code Playgroud)

  • 另一种计算 offsetRight `window.innerWidth - element.getBoundingClientRect().right` 的方法 (3认同)

bit*_*ess 5

几种选择:

1)如果要相对于视口“ offsetRight”,请使用 element.getBoundingClientRect().right;

2)您的示例很好,只需从元素的width + offsetLeft减去父宽度即可。

3)最后,要相对于文档,并加快遍历(offsetParent):

在此示例中,我将伪下拉列表元素放置在引用的元素下方,但是由于避免了一些棘手的z-index问题,并且希望从右侧引用该元素并向左扩展,因此必须附加它到body元素,并从原始父对象获取“ offsetRight”。

...

// Set helper defaults
dropdownElem.style.left = 'auto';
dropdownElem.style.zIndex = '10';

// Get the elem and its offsetParent
let elem = dropdownElemContainer;
let elemOffsetParent = elem.offsetParent;

// Cache widths
let elemWidth = elem.offsetWidth;
let elemOffsetParentWidth = 0;

// Set the initial offsets
let top = elem.offsetHeight; // Because I want to visually append the elem at the bottom of the referenced bottom
let right = 0;

// Loop up the DOM getting the offsetParent elements so you don't have to traverse the entire ancestor tree
while (elemOffsetParent) {
    top += elem.offsetTop;
    elemOffsetParentWidth = elemOffsetParent.offsetWidth;
    right += elemOffsetParentWidth - (elem.offsetLeft + elemWidth); // Most important line like your own example
    // Move up the DOM
    elem = elemOffsetParent;
    elemOffsetParent = elemOffsetParent.offsetParent;
    elemWidth = elemOffsetParentWidth;
}

// Set the position and show the elem
dropdownElem.style.top = top + 'px';
dropdownElem.style.right = right + 'px';
dropdownElem.style.display = 'block';
Run Code Online (Sandbox Code Playgroud)


Ifi*_*Ifi 0

如果您有兴趣使用一些 Js 库,请尝试原型 js 的以下功能 http://api.prototypejs.org/dom/element/offset/

  • 这只是 offsetLeft 已经做的事情的另一种方式,但仍然没有给我 offsetRight。这有什么帮助? (2认同)