代码之家  ›  专栏  ›  技术社区  ›  Curnelious

如何使用scrollTop?

  •  0
  • Curnelious  · 技术社区  · 7 年前

    我的页面分为几个部分,每个部分都是屏幕大小的一个div(100%)。

    每个部分都必须有一个按钮,以全屏向下滚动到下一部分。

    我能够向下滚动一个窗口,而不完全了解我在做什么,并且 如何从每个给定的部分滚动到下一个部分。

    function nextButton() {
    
      $('html, body').animate({
         scrollTop:  $(window).height() 
     }, 1000);
    
    
    }
    
    4 回复  |  直到 7 年前
        1
  •  1
  •   Đào Minh Hạt    7 年前

    该参数 scrollTop

    在您提供的代码中,您将向下滚动1个窗口高度 $(window).height() 所以,如果您想滚动到下一个部分(我假设每个部分的高度等于1个窗口),您需要将其乘以。

    function scrollToSection(sectionNumber) {
    
      $('html, body').animate({
         scrollTop:  $(window).height() * sectionNumber 
     }, 1000);
    
    
    }
    // so if you want to scroll to your first section you call this
    scrollToSection(1) // and so on
    
        2
  •  1
  •   varun agarwal    7 年前

    divs (例如: sections

    // Maintain the current div where the last scroll was performed
    var index = 0;
    
    function nextButton() {
      index += 1;
      var divSections = $('.sections');
    
      // Check to see if more divs exist
      if (!divSections[index]) return;
    
      $('html, body').animate({
         scrollTop:  divSections[index].offset().top
     }, 1000);
    
    
    }
    
        3
  •  1
  •   Jack Bashford    7 年前

    您可以通过向每个jQuery添加ID来使用jQuery平滑滚动 div 要素:

    $("html,body").animate({scrollTop: myDiv.offset().top}, "slow");
    

    为单击或滚动添加事件侦听器,并将其用作事件处理程序,将为您提供所需的内容。

        4
  •  0
  •   Mon    7 年前

    试着给每个div一个id,然后你的按钮添加一个锚定标记,并将其引用到你想要定位的div中。然后在CSS上添加动画效果,添加滚动行为:平滑。

    <div id="#section-one"></div>
    <div id="#section-two"></div>
    <a href="#section-one" class="button"/>
    <div id="#section-three"></div>
    <a href="#section-two" class="button"/>
    
    html {
      scroll-behavior: smooth;
    }