但是,如果在 URL 中添加其他文本,则 active 将丢失。
即使在网址中添加了其他文本,如果它包含特定的“数据目标”,我也希望保持其活动状态。
例如原链接是“link/sub01.html”,但改为“link/sub01.html&page=2”,则样式丢失。
即使添加了文本“&page=2”,如果网址中包含“sub01”,我也希望始终添加 active。
但是我对脚本还不熟悉,所以我不知道在哪里修复它。请帮我。 我不会说英语,所以我用了翻译器。
所以句子可能不太流畅。对不起!
$(document).ready(function() {
var url = window.location;
$('#Nav .Cate li a[href="' + 'data-target' + '"]').parent().addClass('active');
$('#Nav .Cate li a').filter(function() {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});
.Cate {
position: relative;
}
.Cate li {
position: relative;
display: inline-block;
width: 180px;
height: 34px;
float: left;
line-height: 34px;
text-align: center;
border: 1px solid #333;
border-bottom: 0;
border-radius: 15px 15px 0 0;
box-sizing: border-box;
overflow: hidden;
background: rgba(51, 51, 51, 0);
transition: all .35s;
}
.Cate li a {
display: block;
text-decoration: none;
background: rgba(51, 51, 51, 0);
transition: all .35s;
}
.Cate li:hover {
background: rgba(51, 51, 51, 1);
}
.Cate li:hover a {
color: #fff;
}
.Cate li.active {
background: rgba(51, 51, 51, 1);
}
.Cate li.active a {
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Nav">
<ul class="Cate">
<li data-target="index"><a href="index.html">MAIN</a></li>
<li data-target="sub01"><a href="sub01.html">SUB01</a></li>
<li data-target="sub02"><a href="sub02.html">SUB02</a></li>
</ul>
</div>
您需要对代码进行轻微更改,以从 URL 获取准确的
data-target
,然后使相应的 <li>
处于活动状态
$(document).ready(function() {
var urlArr = window.location.pathname.split('/');
var dataTarget = urlArr[urlArr.length-1];
$('.Cate li[data-target='+dataTarget+']').addClass('active');
//rest code will be as it is
});