Javascript scroll to element with animation onclick

大城市里の小女人 提交于 2019-12-08 04:52:55

问题


I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and it's working beautifully animated scrolling down the page to the target element.

The ul is within a fixed position navigation bar.

My question is: what code would be needed to make the animation scroll both up and down when the anchor in the nav is clicked?

var scrollY = 0;
var distance = 10;
var speed = 24;

function autoScrollTo(el) {
  var currentY = window.pageYOffset;
  var targetY = document.getElementById(el).offsetTop;
  var bodyHeight = document.body.offsetHeight;
  var yPos = currentY + window.innerHeight;
  var animator = setTimeout('autoScrollTo(\'' + el + '\')', 24);
  if (yPos > bodyHeight) {
    clearTimeout(animator);
  } else {
    if (currentY < targetY - distance) {
      scrollY = currentY + distance;
      window.scroll(0, scrollY);
    } else {
      clearTimeout(animator);
    }
  }
}

function resetScroller(el) {
  var currentY = window.pageYOffset;
  var targetY = document.getElementById(el).offsetTop;
  var animator = setTimeout('resetScroller(\'' + el + '\')', speed);
  if (currentY > targetY) {
    scrollY = currentY - distance;
    window.scroll(0, scrollY);
  } else {
    clearTimeout(animator);
  }
}
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>

回答1:


Thanks to Dave for steering me away from javascript and on to JQuery. This bit of code is really newb friendly. You don't need to edit it at all, just paste it in your index.html and bam! and it works

<header class="main-header">

                <ul class="main-nav">
                <li><a href="#about">About</a></li>
                <li><a href="#testimonials">Testimonials</a></li>
                <li><a href="#contact">Contact</a></li>
                </ul>
        </header>    

<!-- SMOOTH SCROLL -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
        $(function() {
          $('a[href*=#]:not([href=#])').click(function() {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                $('html,body').animate({
                  scrollTop: target.offset().top
                }, 1000);
                return false;
              }
            }
          });
        });
        </script>
        <!-- End of SMOOTH SCROLL -->   



回答2:


If you're willing to use jQuery this will be much simpler. All you have to do is get the .offset() top of the element you want to scroll to and then animate the scrollTop position using jQuery .animate() function.

function autoScrollTo(el) {
    var top = $("#" + el).offset().top;
    $("html, body").animate({ scrollTop: top }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>



回答3:


I don't have time to put this all in a page to really test it out, but what I would try first is something along these lines:

    if(currentY < targetY-distance){
        scrollY = currentY+distance;
        window.scroll(0, scrollY);
    } else {
        scrollY = currentY-distance;
        window.scroll(0, scrollY);
    }

So instead of clearing the timeout when currentY is greater than the targetY-distance, it scrolls in the opposite direction? Might not work, but worth a shot...



来源:https://stackoverflow.com/questions/27554831/javascript-scroll-to-element-with-animation-onclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!