【发布时间】:2021-12-30 20:22:09
【问题描述】:
如何将 CSS,包括 position: absolute; 包含到容器节点中?即带有position: absolute 的元素应该位于容器节点的左上角,而不是整个文档的左上角。
类似于iframe
使用 shadow DOM 隔离 styleNode 中的 CSS 的示例代码,我无法控制:
test.html
<html>
<body>
<div>this should still be visible and not affected by container styling</div>
<div id="container"></div>
<script>
let container = document.querySelector('#container')
const shadow = container.attachShadow({mode: 'open'});
const styleNode = document.createElement('style');
styleNode.textContent = `
div {
background: blue;
font-size: 32px;
position: absolute;
top: 0;
left: 0;
}
`;
shadow.appendChild(styleNode);
const contentNode = document.createElement('div');
contentNode.textContent = `Hello World`;
shadow.appendChild(contentNode);
</script>
</body>
</html>
期望的结果: 'Hello World' 显示在 'this 应该仍然可见' 下,而不是在它之上。
【问题讨论】:
标签: css shadow-dom