1

我有一个单页站点,其中锚点(# 链接)链接到文档的不同部分。向下滚动/单击时,活动会突出显示。

代码正在工作,但问题是,当我有 href 时<a href="/#anchor">Anchor</a>,它似乎不适用于我的代码。如果我没有正斜杠也有同样的效果,它就像<a href="#anchor">Anchor</a>

任何帮助将不胜感激。

这是两个小提琴

HTML

<ul class="nav">
<!--with the forward slash before the #, it DOES NOT work--->
<li><a href="/#one">One Menu</a></li>
<li><a href="/#two">Two Menu</a></li>
<li><a href="/#three">Three Menu</a></li>
<li><a href="/#four">Four Menu</a></li>
</ul>

<div class="all-sections">
<div id="one" class="section">
<h2>ONE</h2>
</div>
<div id="two" class="section">
<h2>TWO</h2>
</div>
<div id="three" class="section">
<h2>THREE</h2>
</div>
<div id="four" class="section">
<h2>FOUR</h2>
</div>
<div id="five" class="section">
<h2>FIVE</h2>
</div>
</div>

JS

$('a[href*="#"]:not([href="#"])').click( function(event) {
            event.preventDefault();
          var anchor = 0;
         if($(this.hash).offset().top > $(document).height()-$(window).height()){
              anchor=$(document).height()-$(window).height();
         }else{
          anchor = $(this.hash).offset().top - 24 ;
           }
         $('html,body').stop().animate({scrollTop:anchor}, 1000,'swing');
     });
 $('.nav li a').click(function() {
    $(this).parent().find('a').removeClass('highlight');
    $(this).addClass('highlight');
});
$(window).scroll(function() {
    $('.section').each(function() {
        if($(window).scrollTop() >= $(this).offset().top - 50) {
            var id = $(this).attr('id');
            $('.nav li a').removeClass('highlight');
            $('.nav li a[href=#'+ id +']').addClass('highlight');
        }
    });
});

CSS

ul.nav li {
    display: inline-block;
    padding-right: 5px;
}
ul.nav {
    position: fixed;
    width: 100%;
    top: 0;
    background: #39a25a;
    padding: 20px 0;
    margin: 0;
}
.all-sections {
    display: block;
    padding-top: 46px;
}
.section{
  height: 400px;
  width: 600px;
  background: red;
}
.highlight{
  background-color: yellow;
}
4

0 回答 0