滚动到锚点不能在Wordpress页面上工作

时间:2016-06-11 09:31:30

标签: jquery wordpress scroll

this answer开始,我找到了将滚动设置为任意锚点here的代码。

相关网站是Wordpress,因此我将$替换为jQuery

jQuery(document).ready(function() {
    jQuery('a[href^="#"]').on('click', function(event) {
        var target = $(this.href);
        if( target.length ) {
            event.preventDefault();
            jQuery('window').animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    }
});

感谢A Wolff。

但是,单击this page上内容顶部的锚点不会将移动滚动到锚点,它会在点击时立即移动。

e.g。不滚动到锚点的链接:

  • 个人助理
  • 售后服务等

协助表示赞赏。

2 个答案:

答案 0 :(得分:1)

使用滚动事件绑定每个锚点听起来很糟糕。

为什么不在可滚动链接上添加.scroll类并仅在该类上执行脚本?如果您想链接到外部内容怎么办?如果您已将每个链接都设置为可滚动,则无法正常打开它,从而破坏了链接的自然使用。

我想在应该滚动到某处并使用

的链接上添加.scroll
$(".scroll").on('click', function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    var hash = href.split('#');
    var url_hash = '#' + hash[1];
    if ($(url_hash).length > 0) {
        var offset = ($(window).width()<769) ? 20 : 65;
        $('html, body').animate({
            scrollTop: $(url_hash).offset().top-offset
        }, 1000);
    } else{
        location.href = href;
    }
});

这样,您应该指向其他网页或外部内容的常规链接仍然有效。

只是一个建议:)

答案 1 :(得分:0)

这项工作!

jQuery('a[href^="#"]').on('click', function(event) {
    event.preventDefault();

    var anch = this.href.match(/#[a-zA-Z0-9-_]+/i),
        target = jQuery(anch[0]);

    if( target.length ) {

        jQuery('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }
});
相关问题