JS DOM 操作如何影响 CSS 规则匹配?
设置如下:动态生成需要在单个 div 内一起显示的多个项目的内容。布局是:一个外部 div(所有内容的容器)、几个内部 div(内容各不相同)以及每个内部 div 内的一个 div 以及一些文本。
最外层的div从一开始就是页面的一部分,js通过id获取。接下来生成每个内部 div 及其内容,然后将其附加到外部 div。冲洗,重复。
外部 div 有一个与 css 中匹配的类。内部 div 匹配为:
.outerdiv div{...
现在...实际发生的是:内部 div 和内容 div 都匹配外部 div div 规则,尽管其中之一显然是子级(在检查器、Firefox 和 Chrome 中进行了三次检查)内部div而不是外部。
我把它放在两个不同的地方,所以我相当确定我没有疯。有人能告诉我当 DOM 操作发生时 CSS 规则是如何评估的吗? (或者去哪里查找?)
谢谢, ——康拉德
Here is the setup: dynamically generates content for a number of items which need to be displayed together inside a single div. The layout is: An outer div (the container for everything), several inner divs (content varies), and a div inside each other inner div, along with some text.
The outermost div is part of the page from the beginning, and the js gets it by id. Next each inner div and its content are generated and then appended to the outer div. Rinse, repeat.
The outer div has a class that matches it in css. The inner div is matched as:
.outerdiv div{...
now... what actually happens is: both the inner div AND the content div match the outerdiv div rule, despite that one of them is clearly (triple checked in an inspector, Firefox AND Chrome) a child of the inner div not the outer.
I have this in two separate places so I'm fairly sure I'm not crazy. Can somebody tell me how CSS rules are evaluated when DOM manipulations happen? (or where to go to find out?)
Thanks,
-Conrad
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.outerdiv div
选择器选择.outerdiv
中的任何div
,而不仅仅是直接子级。要选择元素的直接子元素,可以使用>
选择器 (IE6 不支持)。至于最后一个问题,CSS 规则总是会被重新评估,即即使在操作 DOM 时,元素也将始终根据 CSS 规则设置样式,并且不会通过 DOM 操作或类似的方式“继承”规则。
The
.outerdiv div
selector selects anydiv
within.outerdiv
, not only direct children. To select a direct child of an element, there's the>
selector (which is not supported by IE6 though).As for the last question, CSS rules are always reevaluated, i.e. even when manipulating the DOM, elements will always be styled according to the CSS rules and don't "carry over" rules through DOM manipulation or anything like that.