我有一个元素,我已经宣布为影子dom,但风格影响其他elelemts [英] I have an element that i have declared as a shadow dom but the style is affecting the other elelemts
问题描述
代码是
<html>
<head>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/document-register-
element/1.7.2/document-register-element.js"></script>
<div id = "1">
<style>
div {
height: 30px;
width: 30px;
background-color: brown;
}
</style>
</div>
<script>
document.getElementById('1').attachShadow({mode: "open"})
</script>
<div id = "2"></div>
<div id = "3"></div>
</body>
</html>
并且jsfiddle链接是 https://jsfiddle.net/o5r229hf/
and the jsfiddle link is https://jsfiddle.net/o5r229hf/
我已将div id 1声明为影子dom但div id为2和3正在获得风格。我可以写下这些元素的顺序吗?
I have declared div id 1 as a shadow dom but div id 2 and 3 are getting the style. Could there be something with the order that i am have written the elements?
推荐答案
您正在创建 < style>
标记为< div id =1>
的子项,而不是shadow DOM的子项。所以< style>
存在于您创建的阴影之外。
You are creating the <style>
tag as a child to the <div id="1">
and not as a child of the shadow DOM. So the <style>
exists outside the the shadow that you created.
CSS必须存在于shadowRoot中影响该shadowRoot中的元素。
The CSS must exist inside the shadowRoot to affect elements within that shadowRoot.
shadowRoot之外的任何CSS都不应该影响shadowRoot中的元素。 使用广告位时有一个小例外。
Any CSS outside a shadowRoot is not supposed to affect the elements inside the shadowRoot. One minor exception is when using slots.
如果您的代码仅限于上面显示的内容,那么您需要通过执行以下操作将CSS移动到shadowRoot中:
If your code is limited to what you are showing above then you need to move the CSS into the shadowRoot by doing something like this:
var el = document.getElementById('1');
var s = el.attachShadow({mode: "open"});
while(el.firstElementChild) {
s.append(el.firstElementChild);
}
div {
background-color: #F00;
outline: 1px solid black;
height: 80px;
width: 80px;
}
<div id = "1">
<style>
div {
height: 30px;
width: 30px;
background-color: brown;
}
</style>
<div>I1</div>
</div>
<div id="2">
<div>I2</div>
</div>
<div id="3">
<div>I3</div>
</div>
这样做会将< div id =1>
的孩子复制到您创建的shadowRoot中。
What this does is copies the children of <div id="1">
into the shadowRoot that you created.
这会移动< style>
标签,使其仅影响< div>
和没有其他人。
This moves the <style>
tag inside which makes it only affect that <div>
and no others.
如果您的代码不限于上面的内容,那么只需将CSS创建为shadowRoot的子代。
If your code is not limited to something like you have above then just create the CSS as a child of the shadowRoot.
更新:
即使您的代码不在影子DOM中,您也可能需要将CSS添加到容器的影子DOM。 以下是如何处理。
Even if your code isn't in shadow DOM you might need to add your CSS into your container's shadow DOM. Here is how to handle that.
这篇关于我有一个元素,我已经宣布为影子dom,但风格影响其他elelemts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!