【发布时间】:2019-07-15 18:55:35
【问题描述】:
我正在尝试使用 jQuery 构建一个功能,该功能将根据标题部分动态创建哈希锚链接。现在,如果有一个带有此哈希的 URL,那么我想在页面加载时滚动到该部分。问题出在页面加载时,浏览器将滚动到正确的锚点,然后跳转回顶部。所以它可以工作,但不会留下来。
我知道这里的问题是页面加载时锚标记不存在,因此我必须等待添加元素才能执行任何滚动。
我尝试做的是:
- 缓存哈希和 URL
- 获取哈希
- 从 URL (
replaceState) 中删除它 - 使用缓存的哈希滚动到该部分
- 再次使用
replaceState将 URL 返回到其原始阶段
var HeaderAnchors = function(el){
//setup some variables
this.$el = $(el);
this.$headers = this.$el.find( 'h2, h3' );
this.headerSlugs= [];
this.urlHash = window.location.hash;
this.url = window.location.href;
this.init();
};
HeaderAnchors.prototype.init = function(){
new Promise( (resolve, reject) => {
this.createAnchors();
return resolve();
} )
.then( ()=>{
//check if there is hash and if the hash is in the array of headings
if( this.urlHash && this.headerSlugs.includes( this.urlHash.substring(1) ) ){
//disable the anchor from jumping
history.replaceState("", document.title, window.location.pathname);
//smooth scroll to the stop of the hash, which has the same ID as the hash
Foundation.SmoothScroll.scrollToLoc( this.urlHash, {
threshold: 50,
offset: 100,
animationDuration: 200
}, ()=>{
//add the url back to
window.history.replaceState({ path: this.url }, '', this.url);
});
}
} );
};
HeaderAnchors.prototype.createAnchors = function(){
this.$headers.each( ( index, val )=>{
const heading = $(val);
const headingText = heading
.text()
.toLowerCase()
.trim()
.replace( /[^\w\s]/gi, '' )
.replace(/ +/g,'-');
this.headerSlugs.push( headingText );
let hashIcon = $('<span />')
.addClass( 'fas fa-hashtag' )
.attr({
'aria-hidden' : 'true'
});
let anchor = $('<a />')
.attr({
'href' : `#${headingText}`,
'class' : 'c-anchor-hash__link'
})
.append( hashIcon );
heading
.addClass( 'c-anchor-hash' )
.attr( { 'id' : headingText} )
.prepend( anchor );
} );
};
我希望锚点滚动到动态创建的锚点...确实如此...但随后又跳回...
任何帮助都会很棒。谢谢!
【问题讨论】:
-
你是否已经尝试过使用
setTimeout在加载完所有内容后运行滚动功能? -
@mjw 是的,我已经尝试设置
setTimeout大约 200 毫秒......它通过向下滚动来工作,然后它跳回页面顶部
标签: jquery scroll url-rewriting anchor