5

preventDefault在这样的元素事件中使用过:

$('#element').click(function (e) {
    do stuff...
});

现在,我有一个函数,该函数已经接受了我想使用的参数,preventDefault但我不确定如何:

<a href="#services" id="services_link" class="services" onclick="sectionScroll('services')">Services</a>


function sectionScroll(id) {
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}

我尝试使用 return false 代替,但这会在单击链接时导致一些闪烁。

如何添加preventDefault到上述功能?

编辑

我最初的问题是在具有其他参数的函数中使用 preventDefault 。最后我不需要使用内联javascript(看起来没有办法避免它),所以这就是我使用的。我认为它很整洁:

<a href="#services" class="menu-link">Services</a>


   $('.menu-link').click(function (e) {
        e.preventDefault();
        var location = $(this).attr('href');
        history.pushState(null, null, location)
        $('html, body').animate({
            scrollTop: $(location).offset().top
        }, 1000);
    });
4

5 回答 5

13

好吧,如果你真的想使用内联事件处理程序(虽然不推荐),试试这个:

<a href="#services" id="services_link" class="services"
   onclick="sectionScroll('services', event)">Services</a>

<script type="text/javascript">
function sectionScroll(id, e) {
    e.preventDefault();
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
}
</script>
于 2012-11-21T22:34:28.807 回答
2

您可以使用 jQuery,就像您在其他示例中一样,来处理单击事件:

<a href="#services" id="services_link" class="services">Services</a>

$('#services_link').click(function (e) {
    var id = "services";

    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);

    e.preventDefault();
}

然后,这将允许您调用preventDefault该事件。

这也更好,因为您将不再使用内联 Javascript,并且您的事件逻辑都可以使用一种方法(即 jQuery)来处理,而不是其中一些在 jQuery 和一些内联中。

我建议阅读“我为什么要避免内联脚本? ”以了解为什么应该尽量避免内联脚本。

于 2012-11-21T22:22:21.727 回答
0

您可以从事件处理程序返回 false:

<a href="#services" id="services_link" class="services" onclick="return sectionScroll('services')">Services</a>


function sectionScroll(id) {
    history.pushState(null, null, '#' + id);
    $('html, body').animate({
        scrollTop: $("#" + id).offset().top
    }, 1000);
    return false; // note the addition of return keyword in onclick attribute above
}
于 2012-11-21T22:20:56.533 回答
0

您可以在js本身而不是HTML中分配事件处理程序

<a href="#services" id="services_link" class="services"
                                       data-id="services">Services</a>

/

 $('#services_link').on('click', function(e){
        e.preventDefault();
        // data-id is a HTML5 data attribute

        var id = $(this).data('id');
        history.pushState(null, null, '#' + id);
        $('html, body').animate({
            scrollTop: $("#" + id).offset().top
        }, 1000);
    });
于 2012-11-21T22:24:06.240 回答
-1

如果 .on("click") 将 "overflow:hidden" 添加到正文或 html,页面将滚动到顶部,即使您在回调中使用 e.preventDefalt() 也是如此。

于 2016-04-02T10:00:45.277 回答