选择与类相邻的css id

时间:2017-08-05 09:00:19

标签: css

我想只在跟踪特定类时才选择id。

.class + #id { css }这样的东西会起作用吗?还是有另一种方法可以做到这一点?

我只是在#jp-relatedposts

后才选择.single_job_listing

2 个答案:

答案 0 :(得分:1)

选择器+将有效。如果它位于具有类#jp-relatedposts的元素之后,它将仅选择ID为.single_job_listing的div。

举个例子:

HTML

<div id="main" class="site-main">
  <div class="single_job_listing">
    Your job listing
  </div>
  <div id="jp-relatedposts" class="jp-relatedposts">
    Related Posts
  </div>
  <div id="jp-non-relatedposts" class="jp-relatedposts">
    Non-related Posts
  </div>
</div>

CSS

.single_job_listing + #jp-relatedposts, .single_job_listing + #jp-non-relatedposts {
  background-color: cyan;
}
.jp-relatedposts {
  background-color: #ccc;
}

Running example

青色规则只会选择#jp-relatedposts,而#jp-non-relatedposts将具有默认背景颜色。

您可以从here

了解有关兄弟姐妹选择器的更多信息

答案 1 :(得分:0)

您可以使用<label id="text"> Retrieve data from selected text input among various text inputs with same name & id upon hitting Enter </label> <div> <input type="text" id="inputColors"> </div> <input id="Enter" type="button" value="Enter" /> 例如

<强> HTML

 document.getElementById("Enter").onclick = function() {
 var colors = document.getElementById('inputColors').value;
 var colorslist = colors.split(/[;,]+/);


 $('#text').each(function() {
  $(this).html($(this).text().split(' ').map(function(v) {
    return '<span style="color:' + colorslist[Math.floor(Math.random() * 
 colorslist.length)] + '">' + v + '</span>';
  }).join(' '));
});
} 

-

<强> CSS

>