繁体   English   中英

用平滑滚动突出显示活动锚链接

[英]Highlight active anchor links with smooth scroll

我将平滑滚动脚本与简单的JQuery一起用于锚链接的添加和删除类。

但是两者都分开工作,但是当您将它们放在一起时,锚点突出显示将不起作用。

这是代码

var $navyyLi = $(".navyy li");

$navyyLi.click(function() {
  $navyyLi.removeClass('highlight')
  $(this).addClass('highlight');
});

    $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
          }
        }
      });
    });

JSFIDDLE

一个听众期望点击li ,另一个听众期望点击a

所以我也改变了对a的点击以突出显示:

$(function () {
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                //at this point they will only highlight if clicked anchor is valid to be scrolled
                $(".navyy li").removeClass('highlight'); //<---Remove from all li
                $(this).parents('li').addClass('highlight'); //<---Add the class to the parent li of the clicked anchor
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

小提琴: http : //jsfiddle.net/hLeQy/100/在此更改中,我仅突出显示了锚点是否有效,而不是单击任何锚点时。

如果要突出显示即使锚点无效也无法滚动,请将这两行更改为Click侦听器的第一行。

$(function () {
    $('a[href*=#]:not([href=#])').click(function () {
        $(".navyy li").removeClass('highlight'); //<---Remove from all li
        $(this).parents('li').addClass('highlight'); //<---Add the class to the parent li of the clicked anchor

        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM