【问题标题】:How to Dynamically add anchor tags to URL and scroll to heading if in URL如何动态地将锚标签添加到 URL 并在 URL 中滚动到标题
【发布时间】: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


【解决方案1】:

您的问题的解决方案很简单。你走得太远了。 只需这样做:

$(document).ready(function() {
  $("#gen").click(function() {
    $("#HTMLdy").html('<a href="https://ess.com.ng">Click Me</a>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="HTMLdy"></div>
<button id="gen">Generate Anchor Tag</button>

【讨论】:

  • 感谢@DUG,但不幸的是,我得到了相同的结果。浏览器会跳转锚标签,然后立即跳转回页面顶部。
  • 把锚标签放在一个div和那个div的ID
猜你喜欢
  • 2020-05-17
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2018-07-30
  • 1970-01-01
相关资源
最近更新 更多