平滑滚动+按钮'onclick'功能

时间:2018-06-01 17:39:45

标签: javascript html css

我正在使用以下js来实现页面中页面锚点的平滑滚动:

$(document).ready(function() {
        $("a").on('click', function(event) {
            if (this.hash !== "") {
                event.preventDefault();
                var hash = this.hash;
                $('html, body').animate({
                    scrollTop: $(hash).offset().top
                }, 800, function() {
                    window.location.hash = hash;
                });
            }
        });
    });

这个工作正常,直到我想使用按钮+链接。例如,我有一个按钮:

<button onclick="location.href='#anchor'" class="button">Name</button>

我尝试使用上面的函数,比如将$(“a”)...更改为按钮中的类或id,即$(“。button”)...但是这不是做任何事情。不幸的是,我的js知识就此结束。有谁知道这是否可能?谢谢!

2 个答案:

答案 0 :(得分:1)

问题是您在按钮中立即更改了href。

试试这个:

<button data-hash="anchor" class="button" type="button">Name</button>

$(document).ready(function() {
    $("button.button").on('click', function(event) {
        var hash = $(this).data("hash");
        if (hash) {
            $('html, body').animate({
                scrollTop: $(document.getElementById(hash)).offset().top
            }, 800, function() {
                window.location.hash = hash;
            });
        }
    });
});

答案 1 :(得分:0)

在按钮中设置目标哈希。点击后,阅读并移动

&#13;
&#13;
$(document).ready(function() {
  $("button").on("click", function(event) {
    var hash = $(this).attr("data-target"),
      target = $("#" + hash);

    event.preventDefault();
    $("html, body").animate({
        scrollTop: $(target).offset().top
      },
      800,
      function() {
        window.location.hash = hash;
      }
    );
  });
});
&#13;
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="section-0">Section 1</div>
  <button data-target="section-1">next</button>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <div id="section-1">Section 2</div>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
</body>

</html>
&#13;
&#13;
&#13;