我试图在我的导航列表项上创建一个效果:当鼠标悬停在列表项 anchor 标记上时(或者甚至处于事件状态),<span>
中的图像应替换为图像的彩色版本。文本的颜色和图标的颜色必须一起改变。
我正在使用的代码如下,但这不起作用。看看这里的区别:
所需结果:https://imgur.com/a/wKzwd
实际结果:https://imgur.com/a/QzWwf
nav ul li a:hover,
.active {
color: #3B94D9;
}
nav ul li:hover {
border-bottom: 2px color #3B94D9;
}
span {
margin-right: 4px;
margin-top: 10px;
}
span#home {
width: 20px;
height: 18px;
background: url('../img/home.png') no-repeat;
display: inline-block;
vertical-align: bottom
}
span#home:hover {
background: url('../img/home-hover.png') no-repeat;
}
span#notif {
width: 20px;
height: 18px;
background: url('../img/bell.png') no-repeat;
display: inline-block;
vertical-align: bottom
}
span#notif:hover {
background: url('../img/bell-hover.png') no-repeat;
}
span#msg {
width: 20px;
height: 18px;
background: url('../img/messages.png') no-repeat;
display: inline-block;
vertical-align: bottom
}
span#msg:hover {
background: url('../img/messages-hover.png') no-repeat;
}
<nav>
<ul>
<li><a href="#" class="active"><span id="home"></span> Home</a></li>
<li><a href="#"><span id="notif"></span>Notifications</a></li>
<li><a href="#"><span id="msg"></span>Messages</a></li>
</ul>
</nav>
最佳答案
你很接近,但在你的 CSS 中,只有当它直接悬停在上面时你才会定位跨度。当包含 <a>
时,您需要定位它悬停在上面。
所以不要使用:
span#home:hover {
background: url('../img/home-hover.png') no-repeat;
}
当容器是 a
时,使用它来定位跨度元素处于悬停状态:
a:hover span#home {
background: url('../img/home-hover.png') no-repeat;
}
您还可以定位 .active
以这种方式分类,即 a.active span#home
工作代码段:
(请注意,我添加了 block 颜色来代替图标,因为我们没有您的图片可以在此处显示)
nav ul li a:hover,
.active {
color: #3B94D9;
}
nav ul li:hover {
border-bottom: 2px color #3B94D9;
}
span {
margin-right: 4px;
margin-top: 10px;
}
span#home {
width: 20px;
height: 18px;
background: url('../img/home.png') no-repeat;
display: inline-block;
vertical-align: bottom;
}
a.active span#home,
a:hover span#home {
background: url('../img/home-hover.png') no-repeat;
}
span#notif {
width: 20px;
height: 18px;
background: url('../img/bell.png') no-repeat;
display: inline-block;
vertical-align: bottom
}
a.active span#notif,
a:hover span#notif {
background: url('../img/bell-hover.png') no-repeat;
}
span#msg {
width: 20px;
height: 18px;
background: url('../img/messages.png') no-repeat;
display: inline-block;
vertical-align: bottom
}
a.active span#msg,
a:hover span#msg {
background: url('../img/messages-hover.png') no-repeat;
}
/* added for TESTING ONLY as your images are not visible in the snippet */
span#home, span#notif, span#msg{
background-color:#eee;
height: 20px;
width:20px;
}
a.active span#home, a.active span#notif, a.active span#msg,
a:hover span#home, a:hover span#notif, a:hover span#msg{
background-color:#3B94D9;
}
<nav>
<ul>
<li><a href="#" class="active"><span id="home"></span> Home</a></li>
<li><a href="#"><span id="notif"></span>Notifications</a></li>
<li><a href="#"><span id="msg"></span>Messages</a></li>
</ul>
</nav>
关于html - 图标悬停与列表项 anchor 一起悬停时不会悬停 - HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46684889/