gpt4 book ai didi

jQuery 基于哈希的导航与 jquery-bbq 使页面跳转

转载 作者:行者123 更新时间:2023-12-03 22:32:41 26 4
gpt4 key购买 nike

我在 www.tinytoepress.com 上有一个网站,它使用基于 #hash anchor 标记的导航,使用 jQuery 和 jquery-bbq 插件。它工作得很好,只是有时它会导致页面跳到标题下方,就好像它要跳到实际的 <a name...> 一样。标签。但没有这样的标签。

例如,在 OS X 上使用 Chrome,如果我访问主页:

http://www.tinytoepress.com/

然后点击左上角的“商店”链接,我会转到:

http://www.tinytoepress.com/#store

但是,我向下滚动到标题下方,这是不希望的。我希望保持领先地位。

如果我向上滚动并单击“关于”,我会进入“关于”页面,但我会再次向下滚动到标题上方。但是,如果我现在向上滚动到顶部并再次单击“商店”,则无需向下滚动即可进入商店,这是所期望的。

我正在使用简单的.show().hide()控制 div 可见性的方法通过导航点击设置。

有什么想法可以防止在页面中跳转吗?

最佳答案

哈希地址更改时浏览器的默认行为是跳转到代表哈希的 id。例如:http://example.com/some-page#store将在页面上搜索 id 为 store 的元素(<div id="store">...</div>)。如果找到,页面就会跳转到那里。

我建议您设置自定义 data-attr,而不是设置 id 属性。属性。

<div id="store">...</div>将变成<div data-page="store">...</div>在 jQuery 方面,您将替换 $(location.hash).show()与:

$("[data-page='" + location.hash.substring(1) + "']").show()

代码如下所示:

$("a").on("click", function () {

// get the clicked link
var $clickedLink = $(this);

// get the url
var url = $clickedLink.attr("href");

// we search the hashes
if (url[0] !== "#") { return; }

// change the location using js
location.hash= url;

// hide all pages
$("[data-page]").hide();

// show the current page
$("[data-page='" + url.substring(1) + "']").show();

// prevent the default browser behaviour (jumping)
return false;
});

JSFIDDLE

关于jQuery 基于哈希的导航与 jquery-bbq 使页面跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20460733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com