jQuery在单击时滚动到元素,但如果存在则滚动到页面加载

时间:2015-04-21 22:38:43

标签: javascript jquery html

所以我的点击事件向下滚动到hashtag元素类工作正常,但我注意到,如果我从另一个页面请求它没有滚动,所以我添加了窗口加载,它工作可爱,但现在与两位代码一起加载滚动如果一个标签网址存在但点击不再有效...有没有人有更好的解决方案,这两个工作?

JS

// Scroll To # Links
    $('a[href^="#"]').on('click', function(e) {
        if (!$(this).hasClass("menu-button")) {

        e.preventDefault();

        var target = this.hash;
        target = target.replace('#', '');
        var $target = $('.' + target);
            $('html, body').stop().animate({
                    'scrollTop': $target.offset().top
                }, 700, 'swing', function() {

                window.location.hash = '#' + target;
            });
        }

    });

    // Scroll on load if #hashtag set in URL
    $(window).load(function(e){
        // Remove the # from the hash, as different browsers may or may not include it
        var loadTarget = location.hash.replace('#','');

        if(loadTarget != ''){

            e.preventDefault();
            // Clear the hash in the URL
            // location.hash = '';   // delete front "//" if you want to change the address bar
            var $loadTarget = $('.' + loadTarget);
            $('html, body').stop().animate({
                    'scrollTop': $loadTarget.offset().top
                }, 700, 'swing', function() {

                window.location.hash = '#' + loadTarget;
            });

        }
    });

HTML:

<a href="#test">test link</a>

<div class="test" style="margin-top: 1000px;">
  testing content
</div>

1 个答案:

答案 0 :(得分:0)

我设法让代码为我自己工作,所以发布以防万一其他人都需要这样一个类似的解决方案:

JS:

// Scroll To # Links
    $('a[href^="#"], a[href^="/#"]').on('click', function(e) {
        if (!$(this).hasClass("menu-button")) {

        e.preventDefault();

        var target = this.hash;
            target = target.replace('#', '');
        var $target = $('.' + target);
            $('html, body').animate({
                    'scrollTop': $target.offset().top
                }, 700, 'swing', function() {

                window.location.hash = '#' + target;
            });
        }

    });

    $(window).load(function(e){
        // scrollTo if #_ found
        var target = window.location.hash,
            target = target.replace('#', '');
        var $target = $('.' + target);
        console.log(target);
        if (target) {
            $('html, body').animate({
                    'scrollTop': $target.offset().top
                }, 700, 'swing', function() {

                window.location.hash = '#' + target;
            });
        }
    });