【问题标题】:jQuery Click anchor tag prevent page from scrolling to topjQuery Click 锚标记防止页面滚动到顶部
【发布时间】:2013-05-14 06:19:54
【问题描述】:

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

【问题讨论】:

  • 你能提供标记吗,如果你创建一个新的小提琴来看看它是如何工作的。
  • 听起来您需要设置标记样式。 javascript 工作正常。

标签: javascript jquery redirect scroll preventdefault


【解决方案1】:

很好的解决方案:使用历史 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;
    }

【讨论】:

  • 非常感谢,我会用 history api 和 hashbangs 来做这件事,但那也是一个很好的小技巧,也谢谢!
【解决方案2】:
event.preventDefault();
linkLocation = this.href;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-05
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    相关资源
    最近更新 更多