我想在鼠标悬停时在我的 html 中更改多个标签(正文的背景颜色、.text
类的文本颜色和显示 .url
的 url 链接) CSS 中的一个元素。
下面的代码不起作用(出现了 url 标记,但背景颜色和 .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>
最佳答案
不幸的是,您对 CSS 可以实现什么有误解,而您所追求的是需要 Javascript 的帮助。
我在你的代码中看到你有类似的东西;
.img:hover > body {
background-color: black;
}
在DOM中img标签在body里面,简单来说CSS只能影响子元素内部的子元素,所以不可能改变body的背景。例如给定以下 html 结构...
<div class='parent'>
Parent
<div class='child'>Child</div>
</div>
.parent:hover .child { 颜色:红色;
会改变 child 的颜色。
.child { }
无法在 CSS 中做任何事情来影响 .parent 类样式。这是因为浏览器如何遍历 DOM 并应用类。
关于html - CSS:悬停时更改多个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580667/