Smooth scrolling within element, only first link/a

2019-07-08 10:45发布

I am having an issue getting smooth scrolling to work within an overflowed element. The first link/anchor works as expected, but any subsequent links do not scroll to their anchor.

Fiddle: http://jsfiddle.net/BPyVd/1/

<!doctype html>
<html>
<head>

<style>
#container {width: 400px; height: 400px; background: #ccc; overflow-y: scroll}
div > div {margin-top: 500px; height: 1px; background: red;}
</style>
</head>

<body>
<div id="container">
    <a href="#anchor-a">NEXT</a>
    <div id="anchor-a"></div>
    <a href="#anchor-b">NEXT</a>
    <div id="anchor-b"></div>
    <a href="#anchor-c">NEXT</a>
    <div id="anchor-c"></div>
</div>

<script>
$(function() {
  $('a').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) {
        $('#container').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
</script>

</body>
</html>

Any help would be more than appreciated. Thank you.

1条回答
做个烂人
2楼-- · 2019-07-08 11:20

Fixed Script :

<script>
$(function() {
  $('a').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) {
        $('#container').animate({
          scrollTop: $('#container').scrollTop() + target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
</script>
查看更多
登录 后发表回答