首页 > 解决方案 > 动画 jquery 在同一个单击按钮上上下滚动

问题描述

当单击相同的按钮但在不同的滚动区域上时,我正在尝试为滚动设置动画,例如:

但到目前为止,第一个状态正在工作,但第二个状态,如果单击按钮将滚动到第二部分的顶部,而不是页面(正文)的顶部。

$(window).scroll(function() {
  if ($(this).scrollTop() > 300) {
    // if scrolling more than 300px add classes active and up
    $('#scroll-button').addClass('active up').removeClass('down');
  } else {
    // is no scroll or less than 300px, remove class active and add class down 
    $('#scroll-button').removeClass('active up').addClass('down');
  }
});

// is no scroll or less than 300px and #scroll-button.down is clicked, animate scrolling to the next element 
$('.down').on('click', function() {
  $('html,body').animate({
      scrollTop: $("#second").offset().top
    },
    600);
  return false;
});

// if scrolling more than 300px and #scroll-button.up button is clicked, animate scroll to the top of the page
$('.up').on('click', function() {
  $('html, body').animate({
    scrollTop: 0
  }, 600);
  return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="first" class="section"><button id="scroll-button" class="down" type="button">Click Me!</button></div>
<div id="second" class="section">Hi</div>

jsfiddle:http: //jsfiddle.net/uky5fs1d/2/

标签: jquery

解决方案


谢谢你们@DBS 和@AlwaysHelping,根据那篇文章,我已经更改了我的代码,现在正在工作。

// GO TO TOP
$(window).scroll(function () {
    if ($(this).scrollTop() > 300) {
      // if scrolling more than 300px add classes active and up
      $('#scroll-button').addClass('active up').removeClass('down');          
    } else {
      // is no scroll or less than 300px, remove class active and add class down 
    $('#scroll-button').removeClass('active up').addClass('down');
  }
});     


$(document).on('click', '#scroll-button', function(){   
  if ($('#scroll-button').hasClass('down')){
      $('html,body').animate({
        scrollTop: $("#second").offset().top},
        600);
        return false;      
  } else {
    $('html, body').animate({
      scrollTop: 0
    }, 600);
    return false;
  } 
}); 

工作小提琴:http: //jsfiddle.net/uky5fs1d/3/


推荐阅读