几个选择:
1)如果您想要相对于视口的“offsetRight”,请使用element.getBoundingClientRect().right;
2)您的示例很好,只需从元素的宽度+ 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';