防止在单击锚点上跳转到顶部jquery选项卡功能

时间:2013-03-27 13:47:13

标签: jquery tabs anchor

我在I-net中发现了这个非常好的Tab功能。我已经阅读了使用锚点时的标准问题:Windows跳到顶部。尽管有一个e.PreventDefault()和一个Live Eventlistener集成在一起,但它仍然会在单击选项卡时跳到顶部。你能给我一个建议吗?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $('ul.tabs').each(function () {
        var $active, $content, $links = $(this).find('a');
        $active = $links.first().addClass('active');
        $content = $($active.attr('href'));

        $links.not(':first').each(function () {
            $($(this).attr('href')).hide();
        });

        // Binde den click event handler
        $(this).on('click', 'a', function (e) {
            // Mache den alten Tab inaktiv
            $active.removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));
            $active.addClass('active');
            $content.fadeIn(800);
            e.preventDefault();
        });
    });
});
</script>

1 个答案:

答案 0 :(得分:1)

搜索event.preventDefaultstopPropagation return false (经过大量时间测试)
并且,将HREF更改为javascript:void(0)(如果可以)

有时,e.preventDefault无法做到这一点。我发现的最好方法是在名为onclick的函数末尾添加return false。

        // Binde den click event handler
        $(this).on('click', 'a', function (e) {
            e.preventDefault();
            // Mache den alten Tab inaktiv
            $active.removeClass('active');
            $content.hide();
            $active = $(this);
            $content = $($(this).attr('href'));
            $active.addClass('active');
            $content.fadeIn(800);
            e.stopPropagation();
            return false;;
        });
相关问题