简体   繁体   English

正在获取window.scrollTo(0,0); 上班

[英]Getting window.scrollTo(0, 0); to work

I know that this problem got probably asked and solved a thousand times, yet I need advice on my specific case. 我知道这个问题可能被问及解决了上千次,但我需要针对我的具体情况提供建议。

I've set several anchors on my website and I'm using jquery to smoothly scroll between them. 我在网站上设置了多个锚点,并使用jquery在它们之间平滑滚动。 I've been using a #top anchor to scroll to the top of the page and it works. 我一直在使用#top锚点滚动到页面顶部,并且可以正常工作。 The problem is, however, that if I let the button scroll to #top it won't scroll to the absolute top of the page (since I can't set the anchor high enough on the webpage). 但是问题是,如果我让按钮滚动到#top,它将不会滚动到页面的绝对顶部(因为我无法在网页上将锚点设置得足够高)。

I tried to get it work with the window.scrollTo(0, 0); 我试图使其与window.scrollTo(0, 0); command, but I don't know how to get it to work while still having the possibility to scroll to anchors. 命令,但是我不知道如何使其工作,同时仍然有可能滚动到锚点。

I used the following jQuery for the anchor-scrolling: 我使用以下jQuery进行锚定滚动:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

With this HTML: 使用此HTML:

<a href="#top">
    <img alt="" heigth="60" onmouseout="this.src='http://i.imgur.com/0JvWWER.png'" onmouseover="this.src='http://i.imgur.com/Ow7CVn0.png'" src="http://i.imgur.com/0JvWWER.png" width="60" />
</a>

Now, how do I get the window.scrollTo(0,0); 现在,我如何获取window.scrollTo(0,0); to work and how do I implement it in the html body? 工作,以及如何在html主体中实现它?

Thanks in advance. 提前致谢。

As somethinghere says, do a small change here: 作为somethinghere说,这里做一个小的变化:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = $(this).attr("href");

        $('html, body').stop().animate({
            // Change here...
            'scrollTop': ((target === '#top') ? 0 : $(target).offset().top)
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

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

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