jQuery单击锚标记可防止页面滚动到顶部

时间:2013-05-14 06:19:54

标签: javascript jquery redirect scroll preventdefault

我正在使用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;
}

2 个答案:

答案 0 :(得分:1)

良好的解决方案:使用带有hashbangs后备的历史记录api

解决方案不好: 作为一个简单的黑客,您可以使用

捕获当前滚动位置
    $(".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;
    }

答案 1 :(得分:0)

event.preventDefault();
linkLocation = this.href;

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

相关问题