滚动到锚点,同时保留哈希
Scroll to anchor whilst keeping the hash
我有一个导航到各个部分的页面。每一个都为该页面提供了一个锚标记,这样人们就可以轻松地重新访问该部分。我想要的是让正常机制正常工作,但我不希望跳到该部分(按照正常的浏览器行为),而是希望它滚动到那里。
我已经实现了滚动,效果很好,我只是不知道如何保持哈希URL,因为e.preventDefault()
阻止了这种情况的发生。如果我删除这一行,那么页面在滚动之前会闪烁。
$(".navigation a").click(function(e){
$(".navigation a").removeClass("active");
$(this).addClass("active");
if ($(this).attr("href").substring(0,1) == "#"){
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
}
});
我不知道你对旧浏览器的支持有多好,但除此之外,你可以使用pushState函数该url提供了有关如何使用它的文档:)
所有浏览器和IE10都支持(因此没有9或更低版本)
一个无推送状态的解决方案是滚动到适当的高度,然后更改url。如果操作得当,页面不会跳转:)
// you should change class navigation to id navigation, since there probally is only one
$(".navigation".find("a").click(function(e){ // with id this will speed up a bit
//$(".navigation a").removeClass("active");
$(".navigation a.active").removeClass("active"); // with A its faster
$(this).addClass("active");
var anchorDestination = this.href; // save for later, select as little times as possible
//if ($(this).attr("href").substring(0,1) == "#"){
if ( this.href.substring(0,1) == "#"){ // use native JS where possible
e.preventDefault();
var anchorDestination = this.href; // save for later
var $aElem = $(this); // select it once, save it for later
$('html, body').animate({
//scrollTop: $($(this).attr("href")).offset().top
scrollTop: $aElem.offset().top
}, 1000, function(){
window.location = anchorDestination;
});
}
});
相关文章:
- 根据选项卡内部的文本链接中的哈希ID动态选择jqueryUI选项卡
- Steam Web API:I'我不知道该如何处理这个看起来像哈希的url来生成图像
- AngularJS:获取链接中没有哈希的查询字符串值
- 如何在Google chrome安全首选项文件中创建扩展安全哈希代码
- 如何在浏览器重新加载时保存位置哈希状态
- jQuery scrollTop-哈希错误
- 动态添加哈希标记;t工作
- 在Javascript中实现对哈希值的暴力攻击
- 如何在JavaScript/Node中计算SHA256哈希和Base64字符串编码
- 使用Javascript/jQuery以编程方式将当前锚点/哈希/片段附加到任何表单操作url
- 可以在React Native中制作一个自哈希应用程序
- 重定向不带哈希的URL-Ember.JS
- 正在测试主干事件哈希
- 按值对映射/哈希进行排序,保留键
- 为什么我的 JavaScript 哈希带有保留字“toString”作为显示 NaN 的键
- 为什么从其他网络返回会保留最后一个哈希值,同时显示第一个哈希值的内容
- 完全禁用Backbone.js哈希,但将pushState保留在历史记录中
- 滚动到锚点,同时保留哈希
- 如何替换位置哈希并只保留最后一个历史记录条目
- 在ember路由中对模型使用哈希时,不保留模型对象