jQuery 创建一个滚动到顶部按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17643751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:40:20  来源:igfitidea点击:

creating a Scroll To Top button

javascriptjqueryhtmlcssscroll

提问by BrBa

I want to create a similar button as in Lenta.ru, with a smooth retractable effect, can you help me with that?

我想创建一个与Lenta.ru类似的按钮,具有平滑的可伸缩效果,你能帮我吗?

回答by yeyene

Check this DEMO http://jsfiddle.net/yeyene/J3zyq/3/

检查这个演示http://jsfiddle.net/yeyene/J3zyq/3/

$(document).ready(function() {
    $(window).scroll(function() {
        if($(this).scrollTop() > 100){
            $('#goTop').stop().animate({
                top: '20px'    
                }, 500);
        }
        else{
            $('#goTop').stop().animate({
               top: '-100px'    
            }, 500);
        }
    });
    $('#goTop').click(function() {
        $('html, body').stop().animate({
           scrollTop: 0
        }, 500, function() {
           $('#goTop').stop().animate({
               top: '-100px'    
           }, 500);
        });
    });
});   

回答by gmo

Based on this How do I change my background on scroll using CSS?, and a few changes to fit your desire effectwith a little CSS3 & jQ

基于此如何使用 CSS 更改滚动背景?和一些改动,以适应你的欲望effect一点点CSS3 & jQ

HTML

HTML

<div id="up"></div>

CSS

CSS

#up {
    background: url(http://icdn.lenta.ru/assets/icons-s238578731b-c5df9ffc01b66d2cee1e3e3d6d74e49b.png) no-repeat;
    background-position: -2329px 0;
    display: inline-block;
    vertical-align: middle;
    position: fixed;
    right: 100px;
    top: -64px;
    width: 54px;
    height: 54px;
    cursor: pointer;
    opacity: 0;
    -webkit-transition: all 0.5s ease-in-out;
        -moz-transition: all 0.5s ease-in-out;
        -ms-transition: all 0.5s ease-in-out;
        -o-transition: all 0.5s ease-in-out;
        transition: all 0.5s ease-in-out;
}
#up.scrolled{
    opacity:1;
    top: 10px;
}

JS

JS

jQuery(window).scroll(function(){
    var fromTopPx = 200; // distance to trigger
    var scrolledFromtop = jQuery(window).scrollTop();
    if(scrolledFromtop > fromTopPx){
        jQuery('#up').addClass('scrolled');
    }else{
        jQuery('#up').removeClass('scrolled');
    }
});
jQuery('#up').on('click',function(){
    jQuery("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});


Of course you can change the effect and use jQuery animation instead of CSS3... but it will depends on your needs.

当然,您可以更改效果并使用 jQuery 动画代替 CSS3……但这取决于您的需要。

Live example: http://jsfiddle.net/E2aWr/

现场示例:http: //jsfiddle.net/E2aWr/