简体   繁体   English

jQuery-滚动或跳到顶部

[英]jQuery - scroll or jump to top

The context: I have a one page web app. 上下文:我有一个单页Web应用程序。 So there's lots of div 's being hidden at any one time (I'm not sure if this matters). 因此,任何时候都可以隐藏很多div (我不确定这是否重要)。 What I am finding is that when a user is finished with one page (Page X), then they click back (to Page Y) - if they return back to Page X then the position is the same as when they left the page. 我发现的是,当用户完成一页(页面X)时,他们会单击返回(页面Y)-如果他们返回页面X,则位置与离开页面时的位置相同。 The back button is at the bottom, so that's where the user ends up again. “后退”按钮在底部,因此用户可以再次回到该位置。

What I want, is when they return to Page X for them to be at the top of the page so they can start again. 我想要的是当他们返回到第X页时,使他们位于页面顶部,以便他们可以重新开始。 Whether it scrolls back or just jumps back - either way is fine. 无论是向后滚动还是向后跳转-两种方法都可以。

I've tried all of the following with no success: 我尝试了以下所有方法,但均未成功:

    // Scroll to top
    setTimeout(function(){
        alert('scroll');
        $('html, body').animate({scrollTop : 0}, 2000);
    }, 2000);

Adding a div with the id top-anchor at the top and using: 添加一个id为top-anchor的div并使用:

    $('html, body').animate({
       scrollTop: $("#top-anchor").offset().top
    }, 2000);

Having a and using an anchor, with the code below (it only works once though, after that as the hash is already in the URL it no longer works I suppose): 具有a和使用锚点,以及下面的代码(不过,它只能工作一次,在那之后,因为我认为URL中已经存在哈希,所以它不再起作用):

document.hash = '#top-anchor';

Also tried: 还尝试了:

window.scrollTo(0, 0);

No luck. 没运气。

Any alternative ideas are much appreciated. 任何替代的想法都非常感谢。

You can achieve something like that: DEMO : https://jsfiddle.net/yeyene/bpwtLg1w/1/ 您可以实现以下目的:DEMO: https ://jsfiddle.net/yeyene/bpwtLg1w/1/

Not sure how your content divs are shown and hidden, but just get the idea of adding scroll to top of page div part. 不确定内容div的显示和隐藏方式,但是只想将滚动条添加到页面div部分的顶部即可。

Add scroll event on Back button click event, since you already known which page to go, you can scroll to this page's top, by using... 在“后退”按钮单击事件上添加滚动事件,因为您已经知道要转到哪个页面,所以可以使用...滚动到该页面的顶部。

$(element).position().top $(element).position()。top

JQUERY JQUERY

$(document).ready(function () {
    $('input[type=button]').on('click', function(){
        getPageID = $(this).attr('id');

        $('.page').hide(0);
        $('div#'+getPageID).show(0);

        $('html,body').animate({
            scrollTop: $('div#'+getPageID).position().top - 10
        }, 500);
    });
});

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

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