如何在CSS中调用悬停的另一个类



div的类为FIRST。我想在悬停时调用类SECOND。我该怎么做呢?

我使用以下代码:

.first{
background:#F00;
}
.second{
background: #0F0;
}
<div class="first"> This is DIV</div>

您不需要使用额外的类,只需使用伪选择器:hover

为hover添加额外的样式
<style>
.first{
background:#F00;
}
.first:hover{
background: #0F0;
}
</style>

因为我很善良,我已经添加了一个例子,如何做你在纯javascript问也:

<style>
.first{
background:#F00;
}
.second{
background: #0F0;
}
</style>
<div class="first" onmouseover="change()" onmouseout="changeBack()"> This is DIV</div>
<script>
function change() {
    var d = document.getElementsByClassName("first");
    d[0].className += " second";
}
function changeBack() {
    var d = document.getElementsByClassName("first");
    d[0].className = "first";
}
</script>

你的上述方式是不正确的做你正在寻找的。看看下面的内容,你就知道怎么做了。

现场演示

HTML代码

<div class="first"> This is DIV</div>
CSS代码:
.first{
background:#F00;
}
.first:hover{
background: #0F0;
cursor: pointer;
}

你需要声明:hover来创建悬停效果。因此,不是创建一个新类,而是需要将:hover(即伪类)添加到您希望hover工作的类中。这将使您正在寻找的悬停效果。

参考:

W3悬停参考

当一个元素在有限的情况下处于悬停状态时,您可以(使用特定的类)为其设置样式。主要约束:悬停元素必须放在HTML代码之前。

关于+~相邻和一般兄弟组合子的更多信息

.first{
background:#F00;
}
.second{
background-color: #0F0;
}
.first:hover ~ .second {
  background-color: tomato;
}
.first:hover ~ .hello .second {
  background-color: violet;
}
.hello {
  background-color: beige;
}
.hello {
  padding: 1rem;
}
<div class="first"> This is DIV</div>
<div> Some div</div>
<div class="second"> I've class .second</div>
<div class="hello">
  <div class="second"> Child of a (following) sibling of .first</div>
</div>

将第一个框悬停以查看结果

这是你在javascript中应该做的。

document.getElementById('idOfElement')正在获取元素引用。

添加事件。在你的例子中,你需要两个事件,即onmouseover和onmouseleave。

let first = document.getElementById('first'),
    sec = document.getElementById('second');
first.onmouseover = () => {
  sec.style.background = 'black';  
}
first.onmouseleave = () => {
  sec.style.background = 'red';  
}
#first, #second {
  height: 100px;
  width: 100px;
  background: red;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s linear;
}
<div id="first">first</div>
<div id="second">second</div>

你也可以在css上这样做。然而,这是有限的。您无法获得对父元素和前一个兄弟元素的引用。这就是我所知道的。(如果我说错了请指正)。

#first, #second {
  height: 100px;
  width: 100px;
  background: red;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s linear;
}
#first:hover ~ #second {
  background: black;
}
<div id="first">first</div>
<div id="second">second</div>

希望有帮助。欢呼声

最新更新