单击停止脚本滚动回页面顶部

stop script from scrolling back to top of page onclick

本文关键字:顶部 滚动 脚本 单击      更新时间:2023-09-26

我有一个简单的脚本,用于选项卡导航。它只是隐藏并显示一个div。然而,当我从一个选项卡切换到另一个选项卡时,屏幕总是向上平移到顶部!有人知道如何阻止这种情况吗?我的脚本如下:

<script type="text/javascript">
$(document).ready(function() {
    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });
});
</script>

我认为您的点击处理程序需要一个preventDefault()

这将阻止浏览器向顶部平移。

像这样:

//On Click Event
$("ul.tabs li").click(function(e) {
    e.preventDefault();
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tab_content").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active content
    return false;
});

尝试更改您的点击处理程序以针对<a/>标记而不是<li/>标记:

//On Click Event
$('ul.tabs li a').click(function() {
    $('ul.tabs li').removeClass('active');
    $(this).closest('li').addClass('active');
    $('.tab_content').hide();
    var activeTab = $(this).attr('href');
    $(activeTab).fadeIn();
    return false; // prevent default action of <a/> element
});

发生这种情况的原因是,即使在<li/>标记的单击处理程序上返回false,<a/>标记的单击事件也会弹出,并在包含在<li/>标记中的同时被触发。由于没有点击处理程序阻止</a>标记的默认操作,因此页面会跳到顶部——这是假设href属性以哈希开头。

我希望这能有所帮助!