我有:: after伪元素用于导航悬停动画。现在我需要悬停的东西保持在那里根据它活跃的页面。因为我有:: after伪元素,所以我无法使它与jQuery上的addClass一起使用。
<ul class="main-nav">
<li><a href="aboutUs.html">About<div></div></a></li>
<li><a href="services.html">Services<div></div></a></li>
<li><a href="portfolio.html">Portfolio<div></div></a></li>
<li><a href="career.html">Career<div></div></a></li>
<li><a href="contact.html">Contact<div></div></a></li>
</ul>
这是CSS
.main-nav{
float: right;
font-family: 'Open Sans';
font-size: 87.5%;
font-weight:700;
color: #fff;
position: absolute;
right: 140px;
user-select: none;
transition: all .3s ease;
z-index: 10;
}
.main-nav li{
list-style: none;
display: inline-block;
padding-left: 45px;
margin-top: 3.86%;
line-height: 44px;
text-align: justify;
}
.main-nav li a{
text-decoration: none;
color: #fff;
padding-left: 5px;
padding-right: 5px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.main-nav li a:after{
text-align: center;
text-decoration: none;
content:'';
display:block;
width:0; opacity: 0; height:3px;
margin-top: 12px;
background-color:#fff;
transform: translateX(-50%);
transition:all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.main-nav li a:hover:after{width:100%; opacity: 1; transform: translateX(0%);}
可以添加新的css类。这样的类可以在文档加载时动态添加到您感兴趣的li的div子节点:
var currwinAddr = window.location.href.split('/').pop();
$('.main-nav a').filter(function(idx, ele) {
return ele.href.indexOf(currwinAddr) != -1;
}).find('div').addClass('myhighlight');
.main-nav {
background-color: blue;
float: right;
font-family: 'Open Sans';
font-size: 87.5%;
font-weight: 700;
color: #fff;
position: absolute;
right: 140px;
user-select: none;
transition: all .3s ease;
z-index: 10;
}
.main-nav li {
list-style: none;
display: inline-flex; /* changed */
padding-left: 45px;
margin-top: 3.86%;
line-height: 44px;
text-align: justify;
}
.main-nav li a {
text-decoration: none;
color: #fff;
padding-left: 5px;
padding-right: 5px;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.main-nav li a:after {
text-align: center;
text-decoration: none;
content: '';
display: inline-flex; /* changed */
width: 0;
opacity: 0;
height: 3px;
margin-top: 12px;
background-color: #fff;
transform: translateX(-50%);
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.main-nav li a:hover:after {
width: 100%;
opacity: 1;
transform: translateX(0%);
}
/* added */
.myhighlight {
display: block;
height: 3px;
margin-top: -10px;
background-color: #fff;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="main-nav">
<li><a href="aboutUs.html">About
<div></div>
</a></li>
<!-- changed href in the next element for test purposes -->
<li><a href="js">Services
<div class="myclass"></div>
</a></li>
<li><a href="portfolio.html">Portfolio
<div></div>
</a></li>
<li><a href="career.html">Career
<div></div>
</a></li>
<li><a href="contact.html">Contact
<div></div>
</a></li>
</ul>