jQuery点击锚点标记阻止页面滚动到顶部

jQuery Click anchor tag prevent page from scrolling to top

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

我使用jQuery进行页面转换,方法是在页面加载时淡出内容并将其重新淡入,但我的问题是,当我单击链接并调用我的单击函数并重定向页面顶部加载的页面时。有什么办法可以阻止这种行为吗?这是我的页面转换点击功能,提前感谢您的帮助!

链接

<a href="../categories/categories.php"></a>

jQuery

$(".content").fadeIn(750);
$("a").click(function(event){
    event.preventDefault();
    linkLocation = this.href;
    $(".content").fadeOut(500, redirectPage);  
});
function redirectPage() {
    window.location = linkLocation;
}

好的解决方案:使用历史api和hashbangs回退

错误的解决方案:作为一个简单的破解,你可以用捕捉当前的滚动位置

    $(".content").fadeIn(750);
    var offset = window.location.href.match(/offset=('d+)/)
    if(offset){
       $(document).scrollTop(offset[1])
    }
    $("a").click(function(event){
        event.preventDefault();
        linkLocation = this.href + "?offset="+$(document).scrollTop();//pay 
//special attentions to this line will work only for a link without get parameters. 
        $(".content").fadeOut(500, redirectPage);  
    });
    function redirectPage() {
        window.location = linkLocation;
    }
event.preventDefault();
linkLocation = this.href;

感谢团队,请在点击功能启动后将其放在上面两行这将帮助您关闭滚动。