CSS - 选择下一个元素

时间:2016-10-19 22:42:19

标签: html css selector

我不知道如何解释这个问题但是...... 我想选择一个元素,但它与其他元素“相距甚远”

像这样:

<div class="image-div">
    <img src="forest.png" class="image forest">
</div>
<p>
    I want to change the color of this text if the image there ^ is "forest", which I'll change with JS
</p>

.image.forest [some selector idk] p {
    color: red;
}
.image.train [some selector idk] p {
    color: blue;
}

3 个答案:

答案 0 :(得分:2)

如果它适合你,你可以像这样重写它。

<div class="image-div forest">
    <img src="forest.png" class="image">
</div>

<p>I want to change the color of this text if the image there ^ is "forest", which I'll change with JS</p>

<style>
  .forest + p {
    color: red;
  }
  .train + p {
    color: blue;
  }
</style>

答案 1 :(得分:0)

您需要从<div>转到<p><img>,但是从<div>转到.forest会出现问题:没有CSS选择器允许一个人引用DOM树中较高的元素,即没有子到父选择器。

相反,您可以将<div>类应用于<div class="image-div forest"> <img src="forest.png" class="image"> </div> <p> I want to change the color of this text if the image there ^ is "forest", which I'll change with JS </p>

HTML:

.forest + p {
    color: red;
}

CSS:

#method to reduce 2 cat_output objects to one
def makeFinalRec(a: cat_output, b:cat_output): cat_output ={ return cat_output( a.id, 
 if(a.name=="" && b.name!="") b.name else a.name, 
 if(a.legs=="" && b.legs!="") b.legs else a.legs,
 if(a.color=="" && b.color!="") b.color else a.color,
 if(a.tail=="" && b.tail!="") b.tail else a.tail,
 if(a.day=="" && b.day!="") b.day else a.day,
 if(a.ears=="" && b.ears!="") b.ears else a.ears,
 if(a.claws=="" && b.claws!="") b.claws else a.claws ); }

dt.map(x => (x(0), x(1), x(2))).map(x => (x._1.toString,
 cat_output(x._1.toString, 
  (x._2.toString match { case "name" => x._3.toString case _ => ""}), 
  (x._2.toString match { case "legs" => x._3.toString case _ => ""}),
  (x._2.toString match { case "color" => x._3.toString case _ => ""}),
  (x._2.toString match { case "tail" => x._3.toString case _ => ""}),
  (x._2.toString match { case "day" => x._3.toString case _ => ""}),
  (x._2.toString match { case "ears" => x._3.toString case _ => ""}),
  (x._2.toString match { case "claws" => x._3.toString case _ => ""})
) )).reduceByKey((a,b) => makeFinalRec(a,b)).map(x=>x._2).toDF().toJSON.foreach(println)

Output:
{"id":"cat2","name":"Dickens","legs":"4","color":"red","tail":"15cm","day":"","ears":"5cm","claws":""}
{"id":"cat1","name":"Caesar","legs":"4","color":"black","tail":"20cm","day":"","ears":"","claws":""}

答案 2 :(得分:0)

为什么不在森林图像后面直接向p标签添加一个类。

<div class="image-div">
    <img src="forest.png" class="image forest">
</div>
<p class="forest-paragraph"></p>

.forest-paragraph {
     color: #000;
}
相关问题