.preventDefault并返回false都不起作用

时间:2016-10-08 15:24:45

标签: jquery html

编辑:我已经搜索了之前的问题以寻求解决方案,但这些解决方案都没有奏效。请停止标记为重复。

我有一个单页的滚动网站,使用jQuery动画在点击时向下滚动到div,但preventDefaultreturn false都无法阻止默认操作发生,因此不是滚动它只是直接闪烁到各个部分。

$(document).ready(function() {
    $('a[href^="#"]').click(function() {
    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 1500)

    return false;
  });
});
<nav>                   
    <a href="#aboutUs" alt="About Us Button">About Us</a>               
    <a href="#services" alt="Services Button">Services</a>              
    <a href="#blog" alt="Blog Button">Blog</a>
    <a href="#contactUs" alt="Contact Us Button">Contact Us</a>
    <a href="#contactUs" class="button" alt="Enquire Now Button">Enquire Now</a>                
</nav>

1 个答案:

答案 0 :(得分:2)

<script>
    $(document).ready(function() {

        $('a[href="#"]').click(function(e) {
            //this "e" perameter is required to stop the default behaviour
            //but even by default if the "a" tag has a # in its href attribute, 
            //the link will not load or redirect

            e.preventDefault();

            var target = this.hash;
            var $target = $(target);

            $('html, body').stop().animate({
                'scrollTop': $target.offset().top
            }, 1500);

        });

    });
</script>