简体   繁体   English

jQuery滚动到顶部

[英]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... 它只滚动到#content屏幕的顶部...

How does this come? 这是怎么来的?

Here's a jsFiddle: 这是一个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. 为了达到预期的效果,你需要稍微改变你的标记/ css和js逻辑,截至目前你正在隐藏顶部元素,所以一旦完成滚动,底部元素的偏移顶部= 0。

First change is to wrap your html in a <div> we ll give that div an id of #container . 第一个更改是将您的html包装在<div>我们将该div赋予#container的id。 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 : 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: 最后我们需要更改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);

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

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