当该部分的id被点击为一个iink时,如何让页面滚动到一个部分的顶部

时间:2016-12-16 18:15:44

标签: javascript jquery html css

我有一张卡片,上面有一些信息。预期的效果是使下一个和上一个箭头向上或向下滚动到链接上的卡(部分)ID的顶部。这是代码html和jquery:

        <section  class="backgroundBox" id="2">
             <div class="card">
                   <div class="col-sm-5 col-sm-offset-0 right-side smallFontSize top-5112">
                        <h3 class="green">Costs drop significantly as businesses embrace the digital workspace</h3>
                        <p class="center">41% of IT and business decision-makers saw improvements in total management costs by implementing digital workspace efforts, compared with 30% of peers who did not.</p>
                  </div>
                  <div class="col-sm-6 col-md-4 col-lg-5 col-sm-offset-1 col-lg-offset-0 center top-52 top-5112">
                     <img src="http:/slideTwo.png" class="img-responsive">
                   </div>
             </div><!-- card --> 
             <div class="bmr-social col-xs-6">
                    <ul class="social-list">
                         <li><a href=""><img src="/social-fb-500.png" alt="facebook" class="img-responsive icon" height="30px" width="30px"></a></li>
                         <li><a href=""><img src="/social-twitter-500.png" alt="twitter" class="img-responsive icon" height="30px" width="30px"></a></li>
                        <li><a href=""><img src="/social-linkedin-500.png" alt="linkedin" class="img-responsive icon" height="30px" width="30px"></a></li>
                    </ul>
            </div><!-- social -->
            <div class="col-xs-5 col-xs-offset-1 arrows">
                  <p class="right-side social-list"><a href="#1" class="nextPosition up-arrow">&#8593;</a> <a href="#3" class="nextPosition down">NEXT &#8595;</a></p>
           </div><!-- arrows -->
</section>



  <script>
        $('a[href^="#"]').on('click', function(event) {
             $('html, body').animate({
                 scrollTop: $("section").offset().top
              }, 1000);
         });

  </script>

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

以下是使用jQuery和工作演示链接的示例。

function scrollToSection(containerID)
{
   var target = $('#' + containerID);

   event.preventDefault();
   $('html, body').animate({
           scrollTop: target.offset().top
   }, 1000);
}

<button onclick="scrollToSection('section2');">Scroll to Section II</button>

http://blog.regencysoftware.com/post/2015/12/09/jQuery-Scroll-To-Position-Demo