简体   繁体   中英

jQuery scroll back to top

According to this post i asked how to make a scroll method wich shows a element, scrolls to it and hide the element where i came from.

I improved that code, and it works.

But when I try to do this backwards, so from the second screen to the first screen again. Its not working. Its only scrolling to the top of the #content screen...

How does this come?

Here's a jsFiddle:

In order to achieve the desired effect you ll need to change up your markup/css and js logic a bit, as of now you are hiding the top element so once the scroll is done the bottom element's offset top = 0.

First change is to wrap your html in a <div> we ll give that div an id of #container . Second of all we need to set the container's position to absolute so that we can slide it up and down on button click.

The css :

html,body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    overflow:hidden;
}
#page1 {
    height: 100%;
    width: 100%;
}
#content {
    height: 100%;
    width: 100%;
    overflow-y:scroll;
}
#exploreBtn {
    height: 50px;
    width: 50px;
    background-color: red;
}
#goBack {
    position: fixed;
    bottom: 5%;
    right: 5%;
    height: 50px;
    width: 50px;
    background-color: purple;
}
#container {
    position:absolute;
    width:100%;
    height:100%;
}

And finally we need to change up the js:

$(document).ready(function () {
    $('#exploreBtn').on('click', function () {
        showScrollHide('#content', '#page1');
    });

    $('#goBack').on('click', function () {
        showScrollHide('#page1', '#content');
    });
});

function showScrollHide(element, hide) {
    var _ele = $(element),
        _container = $('#container'),
        _ele_top = _ele.offset().top;
    if(_ele_top < 0)
        _ele_top = 0;
    console.log(_ele_top);
    _ele.fadeIn(500, function () {
        _container.stop().animate({
            top: - _ele_top
        }, 1000);
    });
}

We get the desired effect, needs a bit of tweaking but you get the general picture. Hope i helped. The fiddle

把它放在回到顶部按钮的clck处理程序中:$('html')。scrollTop(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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