我想创建CSS规则来设置span
个元素,这些元素会紧跟其他某个范围,并且它们之间没有文本内容。所以我想在这个例子中设置<span class="bar">Second</span>
样式:
<span class="parent">
<span class="foo">First</span>
<span class="bar">Second</span> <!-- this one! -->
</span>
<span class="parent">
<span class="foo">Third</span>
Some text.
<span class="bar">Fourth</span> <!-- but not this! -->
</span>
我已尝试同时使用+
(adjacent)和~
(general)个组合器:
/* colours both "Second" and "Fourth" */
span.foo+span.bar {
color: red;
}
我也试过一些假类:
/* colours "Third", "Some text." and "Fourth" */
span.parent :only-of-type {
color: red;
}
我正在寻找纯CSS中的一些工作解决方案。它可能会使用实验性功能(例如:has
),但Chrome浏览器必须支持这些功能。
答案 0 :(得分:2)
除非开场<span>
紧跟前一个结束</span>
,否则:
<span>...</span><span>...</span>
总是在跨度之间是textnode
- 即使没有可读文本,仍然会有空格。
因此,您需要检查两个条件:
<span>
... <span>
之前?textnode
,立即在<span>
之前......只是空格(或缺席)?如果这两个条件都是true
,那么您可以动态地将一个类添加到正在审核的<span>
中。
工作示例:
var parents = document.getElementsByClassName('parent');
for (var i = 0; i < parents.length; i++) {
var spans = parents[i].getElementsByTagName('span');
for (var j = 1; j < spans.length; j++) {
// Checks preceding textNode for readable text
var followsWhitespace = (/^\s*$/).test(spans[j].previousSibling.textContent);
// Just in case there is no preceding textNode at all
if (spans[j].previousSibling.nodeName === 'SPAN') {
followsWhitespace = true;
}
// Identifies preceding element
var previousElementName = spans[j].previousElementSibling.nodeName;
if ((previousElementName === 'SPAN') && (followsWhitespace === true)) {
spans[j].classList.add('follows-span');
}
}
}
&#13;
.follows-span {
font-weight: bold;
color: rgb(255, 0, 0);
}
&#13;
<span class="parent">
<span class="foo">First</span>
<span class="bar">Second</span> <!-- this one! -->
</span>
<span class="parent">
<span class="foo">Third</span>
Some text.
<span class="bar">Fourth</span> <!-- but not this! -->
</span>
&#13;