One pages/two.php?categor-6ren">
gpt4 book ai didi

javascript - 如何在整个 Bootstrap 中保持事件链接突出显示?

转载 作者:行者123 更新时间:2023-12-01 02:32:28 24 4
gpt4 key购买 nike

任何人都可以帮助我编写一个脚本,使选定的链接突出显示吗?

<div id="productnav">
<nav>
<ul class="nav">
<li><a href="<?php echo $prefix; ?>pages/one.php?category=1" id="navelement1"<?php if ($c == 1) echo ' class="current"';?>>One</a></li>
<li><a href="<?php echo $prefix; ?>pages/two.php?category=2" id="navelement2"<?php if ($c == 2) echo ' class="current"';?>>Two</a></li>
<li><a href="<?php echo $prefix; ?>pages/three.php?category=3" id="navelement3"<?php if ($c == 3) echo ' class="current"';?>>Three</a></li>
<li><a href="<?php echo $prefix; ?>pages/four.php?category=4" id="navelement4"<?php if ($c == 4) echo ' class="current"';?>>Four</a></li></li>
</ul>
</nav>
</div>

下面的代码仅突出显示第一个单击的链接,一旦您在所选页面上选择另一个项目,它就不再保持事件状态。

 Array.prototype.forEach.call(
document.querySelectorAll('#productnav a[href]'),
function(t) {
var hr = t.href.split("/").pop();
if (window.location.href.indexOf(hr) > -1)
t.className = 'active';
else
t.className = '';
}
);

CSS 在这里

#productnav ul li a.active { border-right: solid 8px rgb(200,10,50);  text-decoration: none; background-color: #4E5765; !important; }

谢谢...

最佳答案

您可以使用 JQuery 添加事件类:

function activeClass() {
var fullCurrentURL = window.location.href;
var CurrentURLparts = fullCurrentURL.split("/");
var CurrentURLindex = CurrentURLparts.length - 1;
var CurrentURL = CurrentURLparts[CurrentURLindex];
console.log(CurrentURL);

$('.navbar-nav > li a').each(function() {
var fullLinkURL = $(this).attr('href');
var LinkURLparts = fullLinkURL.split("/");
var LinkURLindex = LinkURLparts.length - 1;
var LinkURL = LinkURLparts[LinkURLindex];
if (LinkURL === CurrentURL) {
$(this).parents("li").addClass("active");
$(this).closest("ul").css('display', 'block');
}
});
}
activeClass();
#productnav ul li.active  a {
border-right: solid 8px rgb(200,10,50);
background-color: #4E5765;
color: #fff;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<nav id="productnav" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li><a href="/about" title="About Us">About Us</a></li>
<li><a href="/js" title="JavaScript">JavaScript</a></li>
<li><a href="/contact" title="Contact Us">Contact Us</a></li>
</ul>
</div>
</nav>

关于javascript - 如何在整个 Bootstrap 中保持事件链接突出显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48215547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com