CSS:在悬停时更改多个标签

时间:2016-11-14 01:21:00

标签: html css

我希望在鼠标悬停时更改我的html中的多个标记(正文背景颜色,.text类的文本颜色和.url的网址链接) CSS中的一个元素。

以下代码无效(显示网址标记,但背景颜色和.text颜色不会改变)。



body {
  background-color: #f1f1f1;
}

div {
  height: 200px;
  width: 400px;
  text-align: center;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -100px;
  margin-left: -200px;
}

.text {
  color: blue;
}

.url {
  z-index: 100;
  position: absolute;
  color: black;
  font-size: 24px;
  font-weight: bold;
  left: 150px;
  top: 100px;
  visibility: hidden;
  opacity: 0;
}

.img {
  position: relative;
  display: block;
  top: 50%;
  left: 50%;
}

.img:hover > body {
  background-color: black;
}

.img:hover > .url {
  visibility: visible;
  opacity: 1;
}

.img:hover > .text {
  color: white;
}

<html>
<head>
  <meta charset="UTF-8"> 
  <link rel="stylesheet" href="index.css">
</head>
<body>

  <div>
    <h1 class="text"> Neon Cabbage </h1>
    <h2 class="text"> 2nd Website </h2>
    <div class="img">
      <a href="main.html"><img src="images/cabbage.jpg" id="cabbage" width="200" height="200" onmouseover="this.src='images/cabbage2.jpg';" onmouseout="this.src='images/cabbage.jpg';"></a>
      <a href="main.html" class="url">click!</a>
    </div>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

不幸的是,你很难理解CSS可以实现什么,你需要Javascript的帮助。

我在你的代码中看到你有类似的东西;

.img:hover > body {
  background-color: black;
}

img标签位于DOM的主体内部,简单地说,CSS只能影响子元素,因此不可能改变主体的背景。例如,给出以下html结构...

<div class='parent'>
   Parent
   <div class='child'>Child</div>
</div>

.parent:hover .child { color: red; }会改变孩子的颜色。

.child { }无法在CSS中执行任何操作来实现.parent类样式。这是因为浏览器遍历DOM并应用类。