gpt4 book ai didi

javascript - 如何将 DIV 及其内容与外部 CSS 隔离

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:36 24 4
gpt4 key购买 nike

我正在创建一个聊天小部件,它将向他网站的正文注入(inject)一个 div。但是,我不希望 div 从网站的默认样式表应用 CSS。

有什么办法可以像这样隔离一个div吗?

大多数现有解决方案都需要更改其网站中的 CSS 代码,这对我来说是不可能的

最佳答案

影子DOM

Shadow DOM v1 的特性当前(不断变化) have growing support ,提供了丰富的可能性,包括 scoped CSS

Shadow DOM v0 was implemented in Chrome/Opera but other browser vendors are implementing v1.
MS Edge status: Under Consideration
Firefox status: in-development

来自 Google Developers: Shadow DOM v1: Self-Contained Web Components :

Hands down the most useful feature of shadow DOM is scoped CSS:

  • CSS selectors from the outer page don't apply inside your component.
  • Styles defined inside don't bleed out. They're scoped to the host element.

CSS selectors used inside shadow DOM apply locally to your component. In practice, this means we can use common id/class names again, without worrying about conflicts elsewhere on the page. Simpler CSS selectors are a best practice inside Shadow DOM. They're also good for performance.

下面,我们attachShadow到一个新的createElement( "div" )我们应用 style.all = "unset" 取消继承所有应用于文档的其余div的规则。

然后,我们在 appendChild( "new_div" ) 之前用我们喜欢的任何内容填充我们的 shadow-root,并提供所需的任何样式。 我们的内容注入(inject)body

结果是风格孤立的内容。

const new_style = document.createElement( "style" ),
new_div = document.createElement( "div" ),
new_p = document.createElement( "p" ),
shadow = new_div.attachShadow( { mode: "open" } );

new_style.textContent = `p {
padding: 1em;
border-radius: 1em;
box-shadow: 2px 2px 15px 5px rgba( 0, 0, 0, .5 );
}`;
shadow.appendChild( new_style );

new_p.textContent = "Shadow DOM FTW \\o/";
shadow.appendChild( new_p );

new_div.style.all = "unset";
document.body.appendChild( new_div );
body {
background: antiquewhite;
}
div {
background: cornflowerblue;
border: 2px grey solid;
border-right: 0;
border-left: 0;
margin: 2em;
}
p {
font-family: "Comic Sans MS";
margin: inherit;
}
<body>
<div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div>
</body>

关于javascript - 如何将 DIV 及其内容与外部 CSS 隔离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45047217/

24 4 0
文章推荐: python - 如何将控件导航到顶级功能
文章推荐: Java:扫描仪的 next() 在 Scite 和命令提示符中的行为不同
文章推荐: python - pandas - 如何将嵌套字典中的数据加载到数据框中?
文章推荐: css -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com