首页 > 解决方案 > 紧接子元素的 CSS 选择器

问题描述

两个简单的 HTML 示例:

<p>
  <i>Some text</i>
</p>

<p>Here's a paragraph that has <i>some text</i>, and then some more</p>

使用 CSS 时,这<i>两种情况下都会选择 's:

p > i {
  border: 1px solid red;
}

>目标<i>中的每一个<p>

我正在寻找的是一种仅针对<i>紧跟在 之后的 's 的方法<p>,换句话说,<i>在第一个示例中针对 the ,但在第二个示例中不针对。以一种+选择相邻兄弟姐妹的方式,但对于相邻的孩子。这可能吗?

我查看了 jQuery 的only-child选择器,但这也针对<i>两个示例中的 's,因为文本(“here's a paragraph...”)不被视为子项。

标签: jquerycss

解决方案


您不能使用 CSS 完成这项工作,但使用 javascript/jquery 您可以选择目标元素,如底部所示。

选择所有i元素并用于.filter()过滤所选元素。在过滤器回调中检查i使用previousSibling属性的先前文本。

$("p > i").filter(function(){
  return this.previousSibling.nodeValue.trim() == "";
}).css("border", "1px solid red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <i>Some text</i>
</p>
<p>Here's a paragraph that has <i>some text</i>, and then some more</p>
<p>
  <i>Some text</i>
</p>
<p>text <i>some text</i>, text</p>


推荐阅读