将平滑滚动应用于现有按钮onclick事件

时间:2018-02-24 15:01:27

标签: javascript jquery html css

我无法将平滑滚动应用到我现有的按钮onclick事件,该事件导航到id =" section3"的div。这是我的HTML / CSS:

<html>
<div id="section1">
  <p>Content</p>
  <button class="button1" onclick="window.location.href='#section3'">Scroll Down</button>
</div>
<div id="section2">
  <p>Content</p>
</div>
<div id="section3">
  <p>Content</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</html>
<style>
#section1, #section2, #section3 {
  height: 100vh;
}
#section1 {
  background-color: blue;
}
#section2 {
  background-color: green;
}
#section3 {
  background-color: yellow;
}
</style>

这是我试过的两个单独的脚本,我认为应该有效,但没有:

$(document).ready(function(){
    $(".button1").click(function(){
        $('html,body').animate({
            scrollTop: $("#section3").offset().top},
            'slow')}
    });
});
$(document).ready(function(){
    $(".button1").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;
            });
        }
    });
});

1 个答案:

答案 0 :(得分:1)

您需要删除在html中添加的onlick事件,然后才能正常工作:

$(document).ready(function() {
  $(".button1").click(function() {
      $('html,body').animate({
          scrollTop: $("#section3").offset().top
        },
        'slow')
  });
});
#section1,
#section2,
#section3 {
  height: 100vh;
}

#section1 {
  background-color: blue;
}

#section2 {
  background-color: green;
}

#section3 {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section1">
  <p>Content</p>
  <button class="button1">Scroll Down</button>
</div>
<div id="section2">
  <p>Content</p>
</div>
<div id="section3">
  <p>Content</p>
</div>