类似于this question,但是我不确定答案是否适用。
我正在尝试做到这一点,以便当您将鼠标悬停在此父div的任何部分上时:
其中的顶部div更改背景颜色:
我有:
/*
Maybe something like this?
var oldBackground;
var parentNode = document.getElementByClassName('item');
var childNodes = document.getElementsByClassName('child');
parentNode.onmouseenter = e => {
var c = e.target.childNodes[0]
c && ((oldBackground = c.style.background) &c.style.background="blue")
};
parentNode.onmouseout = e => {
var c = e.target.childNodes[0]
c && oldBackground && (c.style.background=oldBackground)
};
*/
.dashboard {
display: flex;
}
.dashboard .item {
border-radius: .25rem;
border: 1px solid rgba(0,0,0,.125);
background: white;
text-align: center;
flex-grow: 1;
margin-right: 20px;
width: 20%;
}
.dashboard .item:hover {
cursor: pointer;
border: 1px solid #A7A7A7;
}
.dashboard-item-top {
border-bottom: 1px solid #dfdfdf;
padding: 2px;
font-size: 20px;
transition: background-color 0.5s ease;
/*this background color should change to #F2F3F3 when
.item div is hovered*/
}
.info-block-item {
font-size: 20px;
}
<div class="dashboard">
<div class="item">
<div class="dashboard-item-top">
Classes
</div>
<div class="dashboard-item-bottom">
<span class="info-block-item">0</span>
</div>
</div>
</div>
我不确定从哪里开始。尝试使用JavaScript / jQuery或CSS更好吗?
编辑:已更新,可以运行JSFiddle
答案 0 :(得分:4)
您可以在CSS子元素中添加其他悬停行为,如下所示:
/*on hovering the .item class, manipulate the child with the class .dashboard-item-top*/
.dashboard .item:hover > .dashboard-item-top {
background: #CECECE;
/*any other styles*/
}
.dashboard {
display: flex;
}
.dashboard .item {
border-radius: .25rem;
border: 1px solid rgba(0,0,0,.125);
background: white;
text-align: center;
flex-grow: 1;
margin-right: 20px;
width: 20%;
}
.dashboard .item:hover {
cursor: pointer;
border: 1px solid #A7A7A7;
}
.dashboard .item:hover > .dashboard-item-top {
background: #CECECE;
}
.dashboard-item-top {
border-bottom: 1px solid #dfdfdf;
padding: 2px;
font-size: 20px;
transition: background-color 0.5s ease;
/*this background color should change to #F2F3F3 when
.item div is hovered*/
}
.info-block-item {
font-size: 20px;
}
<div class="dashboard">
<div class="item">
<div class="dashboard-item-top">
Classes
</div>
<div class="dashboard-item-bottom">
<span class="info-block-item">0</span>
</div>
</div>
</div>
答案 1 :(得分:1)
基本上,您想要做的是将父节点悬停在第一个子节点的颜色上。我还假设您想在悬停时将其更改回。因此,您需要添加一个mouseenter和mouseout事件,更改e.target.childNodes[0].style.background
所以,伪代码
var oldBackground;
parentNode.onmouseenter = e => {
var c = e.target.childNodes[0]
c && ((oldBackground = c.style.background) &c.style.background="blue")
};
parentNode.onmouseout = e => {
var c = e.target.childNodes[0]
c && oldBackground && (c.style.background=oldBackground)
};
答案 2 :(得分:1)
以下示例可能仅通过CSS即可帮助您实现所需的功能。
#parent {
cursor: pointer;
}
#parent:hover .parent-highlight {
background-color: red;
color: white;
}
<div id="parent">
<div>hover over me</div>
<div>hover over me</div>
<div>hover over me</div>
<div class="parent-highlight">I get highlighted</div>
</div>