菜单项突出显示,因为我滚动到每个缺陷部分 [英] menu items getting highlight as I scroll to each section with deficiency
问题描述
我刚刚使用此代码突出显示我的菜单,当我向下滚动到我的WordPress网站的每个部分时:
I just used this code to get my menu highlighted as I scroll down to each each section of my WordPress site:
(function($) {
$(document).ready(function(){
$("header nav ul").toggleClass("open");
$("section.container").addClass("section");
});
$(window).scroll(function() {
var position = $(this).scrollTop();
$('.section').each(function() {
var target = $(this).offset().top;
var id = $(this).attr('id');
if (position >= target) {
$('#primary-menu > li > a').removeClass('active');
$('#primary-menu > li > a[href=#' + id + ']').addClass('active');
}
});
});
}(jQuery));
css:
.active{
color: #fff !important;
}
这是链接: http://scentology.burnnotice.co.za
问题是当我一直滚动时,最后一项(联系人)没有突出显示下来联系部分。
另外,如果我单击一个菜单项,它会转到相应的部分,但除非我将页面向下滚动一点,否则该菜单不会突出显示。
我该如何解决?
提前致谢
Here is the link: http://scentology.burnnotice.co.za Problem is that the last item(Contact) is not getting highlighted when I scroll all the way down up to contact section. Also,if I click on a menu item,it goes to the respective section but that menu doesn't get highlighted unless I scroll the page a little bit down'. How can I solve that? Thanks in advance
推荐答案
注意:您似乎从< a href =https://stackoverflow.com/a/32396543/5247200>我对这个问题的回答,我编辑了它以涵盖你的案例。寻找更多代码的其他人可以查看一个代码段。
NOTE: It seems that you took that code from my answer to this SO question, I have edited it to cover your case. Other people looking for more code can check it out for a snippet.
所以,你有两个问题:
- 最后一项没有突出显示。
- 点击菜单时项目,页面滚动到相应的部分,但该菜单不会突出显示,除非向下滚动页面。
问题1
这个很简单,你只是忘了将 id
属性添加到最后一节:)
它应该是:
Problem 1
This one is easy, you just forgot to add the id
attribute to the last section :)
It should be:
<section id="contact" class="container contact-us section">
问题2
您的点击事件开始滚动动画到相应的部分但由于导航栏位于页面顶部,因此您可以使动画在顶部留下一点边距。该边距阻止该部分到达页面顶部,因此菜单项不会突出显示。
Problem 2
Your click event starts a scroll animation to the corresponding section but, since the navigation bar is on the top of the page, you made the animation to leave a little margin on the top. That margin prevents the section from reaching the top of the page, so the menu item doesn't get highlighted.
@Shnibble指向正确的方向,您可以添加 $(窗口).scrollTop()
返回的值的小的正余量(或者 offset()的负值。)top
元素)。
@Shnibble pointed you in the right direction, you can add a small positive margin to the value returned by $(window).scrollTop()
(or a negative one to the offset().top
of the element).
因此,按照您所包含的代码,它将类似于:
So, following the code you have included, it will be something like:
if (position + my_margin >= target) {
保证金可能是高度你的导航栏:
The margin could be the height of your navigation bar:
my_margin = $('#site-navigation').height();
显然,您可以根据需要添加更多或更少的东西来定制它。
You can, obviously, add a little more or less to tailor it to your needs.
这篇关于菜单项突出显示,因为我滚动到每个缺陷部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!