如何让URL含指定data-target时导航保持active状态?
导航项Active状态适配带参数URL的解决方案
问题说明
我希望通过data-target属性为特定URL对应的导航项添加active状态,但当URL添加额外参数(如link/sub01.html变为link/sub01.html&page=2)时,active状态会丢失。需要实现:即使URL带有额外内容,只要包含对应li标签的data-target值(例如sub01),就始终为该导航项添加active状态。
原代码
HTML代码
<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>
CSS代码
.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; }
原JS代码(存在问题)
$(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'); });
修改后的解决方案
HTML和CSS代码无需修改,仅替换JS代码即可:
修改后的JS代码
$(document).ready(function() { // 获取当前页面的完整URL(包含参数) const currentUrl = window.location.href; // 遍历所有导航项,逐一匹配判断 $('#Nav .Cate li').each(function() { // 取出当前导航项的data-target值 const targetName = $(this).data('target'); // 构造对应的目标页面文件名(和href保持一致) const targetPage = `${targetName}.html`; // 检查当前URL是否包含目标页面文件名,忽略后续参数 if (currentUrl.includes(targetPage)) { $(this).addClass('active'); } }); });
代码说明
- 不再直接匹配完整URL,而是通过
includes()方法检查当前URL是否包含导航项对应的目标页面文件名(如sub01.html),无论URL后是否带有参数,只要核心文件名存在就能匹配成功。 - 利用
data-target的值直接构造目标文件名,确保和导航项的href路径完全对应,避免匹配错误。 - 遍历所有导航项逐一判断,确保符合条件的导航项能准确添加
active状态。
内容的提问来源于stack exchange,提问作者Yeppeuda
相关产品推荐
相关产品推荐

