【问题标题】:Using one Button to scroll down and to top, depending on scroll value使用一个按钮向下滚动和向上滚动,具体取决于滚动值
【发布时间】:2017-06-24 20:57:14
【问题描述】:

我尝试仅使用一个按钮在 scrollTop 小于 250 时向下滚动,并在滚动高度高于 250 时滚动回顶部。

我想出的系统在向下滚动时工作正常,但在滚动回顶部之前卡住了一段时间:

CSS:

.rotate{
    -webkit-transform: rotate(180deg);
    -moz-transform: rotate(180deg);
    -o-transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    transform: rotate(180deg);
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    box-shadow: 0 -1px 1.5px 0 rgba(0,0,0,.12), 0 -1px 1px 0 rgba(0,0,0,.24);
}
.totop{
    width: 50px;
    height: 50px;
    position: fixed;
    bottom: 15%;
    background-color: #ffffff;
    left: 50%;
    margin-left: -25px;
    z-index: 1;
    border-radius: 50px;
    box-shadow: 0 1px 1.5px 0 rgba(0,0,0,.12), 0 1px 1px 0 rgba(0,0,0,.24);
    text-decoration: none;
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
}
.totop i{
    display: block;
    margin: auto;
    width: 25px;
    height: 25px;
    font-size: 25px;
    line-height: 50px;
    color: #757575;
}

HTML:

<a class="totop ripple" data-ripple-color="#89669b" href="#"><i class="material-icons">arrow_downward</i></a>

Javascript:

$('.totop').removeClass("rotate");
$(".totop").click(function(event){
        $('html, body').animate({scrollTop: '+=300px'}, 800);
});

$(document).scroll(function() {
var y = $(document).scrollTop();
if (y > 250) {
        $('.totop').addClass("rotate");
        $(".totop").click(function(event){
            $('html, body').animate({scrollTop: '0'}, 800);
        });
      } else if (y <= 250){
        $('.totop').removeClass("rotate");
        $(".totop").click(function(event){
            $('html, body').animate({scrollTop: '+=600px'}, 800);
        });
      }    
});

【问题讨论】:

    标签: jquery html button scroll


    【解决方案1】:

    这是一个将类切换和 onclick 事件分开的工作解决方案:

    $(document).scroll(function() {
      var y = $(document).scrollTop();
      if (y > 250) {
          $('.totop').addClass("rotate");
      } else if (y <= 250){
          $('.totop').removeClass("rotate");
      }
    });
    
    $(".totop").click(function(event){
        var y = $(document).scrollTop();
        var down = y+600;
            if($(this).hasClass('rotate')) {
            $('html, body').animate({scrollTop: '0'}, 800);
        } else {
            $('html, body').animate({scrollTop: down}, 800);
        }
    });
    

    在这里提琴:https://jsfiddle.net/vbt7ypqq/

    【讨论】:

    • 谢谢老哥,不胜感激
    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2015-05-18
    • 2023-04-10
    • 2015-06-07
    • 2012-10-27
    相关资源
    最近更新 更多