2つのDOMノードの共通のオフセット親を取得しようとしていますが、両方のノードがドキュメント内にあるときに問題なく動作しますが、影のDOMにあります。私はシャドウDOMとcreateRange
作業を行うことができますどのようにShadow DOM内の2つの要素のうちの1つとgetRangeを使用
function isOffsetContainer(element) {
return element.firstElementChild.offsetParent === element
}
function findCommonOffsetParent(element1, element2) {
const range = document.createRange();
if (element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING) {
range.setStart(element1, 0);
range.setEnd(element2, 0);
} else {
range.setStart(element2, 0);
range.setEnd(element1, 0);
}
const { commonAncestorContainer } = range;
// When one of the two elements is inside Shadow DOM, the `commonAncestorContainer`
// returned is actually one of the two given elements in the range...
// For demo purposes, we detect this situation and we `console.log` it
if ([element1, element2].includes(commonAncestorContainer)) {
console.log('Shadow DOM ');
} else {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
const offsetParent = commonAncestorContainer && commonAncestorContainer.offsetParent;
if (!offsetParent || offsetParent && offsetParent.nodeName === 'BODY') {
return window.document.documentElement;
}
return offsetParent;
}
}
// Demo code
const reference = document.createElement('div');
reference.className = 'reference';
reference.innerText = 'reference';
const shadowParent = document.createElement('div');
document.body.appendChild(shadowParent);
document.body.appendChild(reference);
const shadow = shadowParent.createShadowRoot();
document.body.appendChild(shadow);
const popper = document.createElement('div');
popper.className = 'popper';
popper.innerText = 'popper';
shadow.appendChild(popper);
findCommonOffsetParent(popper, reference);
.popper {
width: 100px;
height: 100px;
background: red;
}
.reference {
width: 100px;
height: 100px;
background: blue;
}
?
が、私は同様のソリューションhttps://github.com/FezVrasta/popper.js/pull/201/files#diff-3841f93aefe44e3ce876c730b18768d7R22 –
になってしまった、ありがとうあなたは私よりも速かった! – Supersharp
少なくとも私の解決策は奇妙なことではないことは分かっています。なぜなら、少なくとも世界の他の人は同じことで終わったからです。 –