繁体   English   中英

链接到WP导航不同页面上的锚点

[英]Link to anchor on different page from WP nav

我有一个导航栏,该导航栏链接到起始页上的不同锚点。 当我使用首页上导航中的链接时,它会平滑滚动到正确的ID。 但是当我转到子页面/其他页面时,我希望导航栏将我直接发送回首页和所选的ID(锚定)。 我认为平滑滚动javascript有一些冲突,但我可能是错的。

我的自定义WP主题的名称是:Fitnesstravels。

导航栏由Wordpress菜单ex中的自定义链接组成:

网址: http://localhost:8080/fitnesstravels/#destinations

名称:目的地

当我转到以下子页面时: http://localhost:8080/fitnesstravels/destinations/rhodos

我的导航栏中名为“目的地”的菜单链接已链接到http://localhost:8080/fitnesstravels/#destinations锚点(如果我单击了“在新标签页中打开链接”,则我被发送到了正确的位置。)我尝试仅使用菜单链接时会发生这种情况。

js:

$('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) {
     e.preventDefault();
     var target = this.hash,
     $target = $(target);
     $('html, body').stop().animate({
          'scrollTop': $target.offset().top-50
     }, 1200, 'swing', function () {
          window.location.hash = target;
     });
});

问题是e.preventDefault()

我已经完全按照您在网站上尝试的方式进行了操作,并且以您描述的相同方式,唯一的不同是我的平滑滚动jQuery不使用preventDefault

这是我的平滑滚动jQuery(的相关部分):

var $root = $('html, body');

$( ".navbar" ).on( "click", "li a", function(  ) {
    var pageanchor = this.hash;
    if (pageanchor)
        $root.animate({ scrollTop: $(pageanchor).offset().top}, 500);
});

如果我更改代码以使用您的变量名和动画设置,除了preventDefault之外,它几乎与您的代码相同。

$(document).ready(function() {
    $('.nav.navbar-nav a, .arrow a[href^="#"]').on('click',function (e) {
        var target = this.hash;
        if (target)
            $('html, body').animate({ 
                scrollTop: $(target).offset().top-50
            }, 1200, 'swing', function () {
                window.location.hash = target;
        });
});

暂无
暂无

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

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