我这里有一个html,它有一个js-nav和data-id类,我想用它们来确定当前的滑动菜单。
<a class="nav-link js-nav" data-id="about" href="/#about">About</a>我在代码中所做的是首先获取当前的url,然后将其过滤掉,直到获得当前的#about url。然后,on会通过在前面添加data-id字符将其与#进行比较。然后如果它们相等,我必须在锚标记js-nav上添加一个类active-menu,然后突出显示它,但我还需要删除所有项上的任何现有active-menu类。到目前为止,我的代码如下。
var url = window.location.href;
var link = url.split('/')[3];
var item = $('a[data-id]');
if ('#' + item == link){
$('a.js-nav').toggleClass('active-menu')我想在这里实现的是,我需要通过在当前滑动锚点项目上添加active-menu类来突出显示当前菜单,这是通过URL确定的。我还需要在添加任何锚点时移除任何现有的active-menu类,以确保只有一项具有活动类。
现在,这段代码不起作用,特别是在项目变量中添加#字符以便将其与链接进行比较的部分。
如何修复代码以获得正确的输出?}
发布于 2020-02-03 22:10:57
你的代码中有一些错误:
var item = $('a[data-id'); //Missing ] at the end如果想要获取data-id值,则需要使用$('.nav-link').data('id');
然后从所有元素中删除所有.active-menu类:
$('.active-menu').removeClass('active-menu');最后,将类添加到所需的元素中:
$('#' + item).toggleClass('active-menu');发布于 2020-02-03 22:11:32
var url = window.location.href;
// var link = url.split('/')[3]; --> This won't always work because it will depend on the number of slashes you have, so I would replace it with
var link = window.location.hash
$('a.js-nav.active-menu').removeClass('active-menu'); //will remove all actives
$('a.js-nav[data-id="' + link.replace('#', '') + '"]').addClass('active-menu'); //will add the class to the one you want发布于 2020-02-03 22:10:47
function activateNavLink() {
var url = window.location.href;
var link = url.split('/')[3];
link = 'about'; // <<<< for demo only remove this line
$('.nav-link.js-nav').removeClass('active-menu'); // remove all active
$('a[data-id="' + link + '"]').addClass('active-menu'); // add active to only this
}
activateNavLink();.active-menu {
background: blue;
color: white;
}<a class="nav-link js-nav" data-id="about" href="/#about">About</a> -
<a class="nav-link js-nav" data-id="contactus" href="/#contactus">Contact Us</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
https://stackoverflow.com/questions/60040804
复制相似问题