使用固定按钮向上/向下滚动到部分 [英] scroll up/down to sections with fixed buttons

查看:50
本文介绍了使用固定按钮向上/向下滚动到部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个脚本,用于向上/向下滚动到页面的section标签.我的源代码如下:

I want to build a script for scrolling up/down to section tag of page. My source code looks like this:

HTML:

<div class="move">
    <div class="previous">UP</div>
    <div class="next">DOWN</div>
</div>
<section>First</section>
<section>Second</section>
<section>Third</section>
<section>Fourth</section>

CSS:

section{
    height: 400px;
    border: 1px solid black;
}

.move{
    position: fixed;
    bottom: 0;
    right: 0;
}

我还有两个固定在页面底部的按钮.

I also have two buttons which are fixed at the bottom of the page.

现在,我想制作一个脚本来向上/向下滚动到各个部分.如果有人在这种情况下刷新网页该怎么办-例如第2部分将位于页面顶部?如何确定当前页面顶部最近的部分?

Now I want to make a script for scroll up/down to sections. What if somebody refresh web page in situation - for example section 2 will be at the top of the page? How to determine which section is currently nearest top of the page?

这里是小提琴.

推荐答案

下面的示例使用页面的当前滚动位置来确定需要滚动到哪个section元素,而不是显式变量,后者将变得不同步.如果用户要手动滚动到其他部分,请按导航按钮.

The following example uses the current scroll position of the page to determine which section element needs to be scrolled to rather than an explicit variable, which would become out of sync if the user were to manually scroll to a different section then press the nav buttons.

$(function() {
    var $window = $(window);
    $('.next').on('click', function(){
        $('section').each(function() {
            var pos = $(this).offset().top;   
            if ($window.scrollTop() < pos) {
                $('html, body').animate({
                    scrollTop: pos
                }, 1000);
                return false;
            }
        });
    });

    $('.previous').click(function(){
        $($('section').get().reverse()).each(function() {
            var pos = $(this).offset().top;   
            if ($window.scrollTop() > pos) {
                $('html, body').animate({
                    scrollTop: pos
                }, 1000);
                return false;
            }
        });
    });
});

工作示例: JSFiddle

这篇关于使用固定按钮向上/向下滚动到部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆