代码之家  ›  专栏  ›  技术社区  ›  Sam Malayek

尝试在加载新选项卡时滚动到目标ID

  •  1
  • Sam Malayek  · 技术社区  · 5 年前

    我试图编写一个函数来读取URL,如果URL包含 # ,然后显示跳到document元素,其中 id=<string following #> . 所以 myurl.com/#overview 应该滚动到document元素 id='overview' .

    我还想在所有文档元素加载后在页面加载时运行此函数。

    我已经在浏览器控制台中运行了这个函数,它可以工作。但当我在 DOMContentLoaded 事件, target 总是 null .

    const mfn = function () {
      console.log('test');
      const url = window.location.href;
      const idIndex = url.indexOf('#');
      if (idIndex > -1) {
        const targetId = url.substr(idIndex + 1);
        console.log(targetId);
        const target = document.getElementById(targetId);
        console.log(target);  // null :(
        target.scrollIntoView();
      }
    };
    document.addEventListener("DOMContentLoaded", mfn);
    

    有更好的活动吗?

    更新: 我知道这是默认的。出于某种原因,在我的盖茨比耶斯博客里,它没有发生。@阿伦·普洛查兹克的回答揭示了一个解决方案,但这很奇怪。会问在Gatbsy github的问题。

    3 回复  |  直到 5 年前
        1
  •  1
  •   Aaron Plocharczyk    5 年前

    您不必编写额外的JavaScript来使页面跳转到URL中ID为的元素。它应该已经作为默认行为执行了,如下所示: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event#Examples . 您所指的这个元素是否有可能在以后通过JavaScript DOM操作动态填充到该页面?如果是,你需要打电话 mfn 之后 元素被添加到页面中。如果找不到添加到页面的位置,请尝试:

    const url = window.location.href;
    const idIndex = url.indexOf('#');
    if(idIndex > -1){
        const targetId = url.substr(idIndex + 1);
        var elementLoadedCheck = setInterval(function(){
            if(document.getElementById(targetId)){
                const target = document.getElementById(targetId);
                console.log(target);
                target.scrollIntoView();
                clearInterval(elementLoadedCheck);
            }
        }, 100);
    }
    

    你也有可能把身份证打错了。

        2
  •  0
  •   Azad    5 年前

    在我的示例服务器中,我有两个文件, index.html , test.html

    我用 http-server 为这两个文件服务,

    http-server .

    当我单击索引文件中的链接时 测试.html 在“新建”选项卡中打开并滚动到相关ID。

    index.html索引

    <html>
        <header>    
        </header>
        <body>
            <a href="/test.html#two" target"blank">two</a>
            <a href="/test.html#three" target"blank">three</a>
        </body>
    </html>
    

    测试.html

    <html>
        <header>    
        </header>
        <body>
            <div id="one" style="height:100vh; background:red"> </div>
            <div id="two" style="height:100vh; background:green"> </div>
            <div id="three" style="height:100vh; background:yellow"> </div>
        </body>
    </html>
    
        3
  •  0
  •   Barry Chapman    5 年前

    这是标准行为,不需要额外的JavaScript。

    如果你想的话 animate 卷轴,那可能吧完成CSS转换。或者你可以使用JS。

    无论如何,基本行为都会显示在这个小提琴上:

    https://jsfiddle.net/barrychapman/82qcvkem/