【问题标题】:Smooth scrolling through element by clicking anchor with jQuery通过单击带有 jQ​​uery 的锚点来平滑滚动元素
【发布时间】:2013-12-01 02:31:12
【问题描述】:

我的页面左侧有一个固定的 div (#navigation),右侧有一个可滚动的 div (#content)。单击#navigation 中的链接时,它应该会触发平滑滚动到#content 的更正部分。发生的情况是,在您第二次单击链接后,它会转到#content 的错误部分。您可以在http://germanespitia.com中查看所有实际源代码

所以..

导航:

<div id="navigation">
        `enter code here`    <div class="nav-item" data-page="about-me">
            <a href="#about-me" >
            </a>
        </div>
        <div class="nav-item" data-page="projects">
            <a href="#projects" >
            </a>
        </div>
        <div class="nav-item" data-page="portfolio">
            <a href="#portfolio" >
            </a>
        </div>
        <div class="nav-item" data-page="contact">
            <a href="#contact" >
            </a>
        </div>
    </div>

内容:

<div id="content">
        <div class="section" id="about-me">
        </div>
        <div class="section" id="projects">
        </div>
</div>

jQuery:

$('#navigation a').click(function() {
   var goTo = $($(this).attr('href')); // selects element that was clicked
   var offset = goTo.offset(); //grabs position of element
   $('#content').animate({
      scrollTop: goTo.offset().top
   }, 1000);
   return false;
   $('#about-me h1').text(goTo.attr('href'));
   });

【问题讨论】:

    标签: jquery html css scroll smooth-scrolling


    【解决方案1】:
    $('#navigation a').click(function() {
       var goTo = $($(this).attr('href')); // selects element that was clicked
       var offset = goTo.offset(); //grabs position of element
       $('#content').animate({
          scrollTop: goTo.offset().top
       }, 1000);
       return false;
       $('#about-me h1').text(goTo.attr('href'));
       });
    

    您滚动到的偏移量是您应该修复的元素中当前位置的偏移量

    scrollTop: goTo.offset().top
    

    到

    scrollTop: $('#content')[0].scrollTop + goTo.offset().top
    

    可能有效

    【讨论】:

      【解决方案2】:

      只有当偏移量很大时滚动才能正常工作,它在您传递给animate 函数的 1000 毫秒内运行得更快。一种想法是根据当前偏移量与我们想要到达的偏移量的差异来计算完成动画所需的时间。像这样:

      $('#navigation a').on("click", function () {
          var gt = $($(this).attr('href')),
              ofs = gt.offset(),
              tp = ofs.top,
              crOff = $('#content').scrollTop(),        
              anim = Math.abs(crOff - tp) * 100; //ESTIMATE TIME TO ANIMATE 
          if (x > 3000) x = 3000;//IF GAP IS TOO LARGE, IT IS PAINFULLY SLOW
          $('#content').stop().animate({
              scrollTop: tp
          }, anim); //USE anim VARIABLE TO CONTROL ANIMATION TIME
          event.preventDefault();
          event.stopPropagation();
      });
      

      看看这个小提琴:http://jsfiddle.net/Vqce7/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多