最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Links to anchors within a document do not scroll the page with iframe using srcdoc - Stack Overflow

programmeradmin2浏览0评论

I have documents with links to internal anchors within a document. That is to say, I have a document that has a link in the form <a href="toc">Table of Contents</a> that when clicked will scroll to the anchor <a id="toc">Table of Contents</a>.

However if I put this document in an iframe using srcdoc, adding <base href="about:srcdoc" /> to the head of my document to work around the issues How to make href anchors in iframe `srcdoc` actually work describes, I can see window.location.hash in my iframe update correctly, but the page does not actually scroll. I've tried this using Windows 64bit Firefox 136.0.4 and Chrome 134.0.6998.178.

To see this for yourself:

<html>
  <head></head>
  <body>
    <div id="div1" style="height: 4000px">
      First div
      <a href="#div2">Go to second div</a>
    </div>
    <div id="div2" style="height: 4000px">
      Second div
      <a href="#div1">Go to first div</a>
    </div>
  </body>
</html>

Is a simple test document. If you save it as a .html file, load it in a browser, and click the links, you'll see the page scroll.

<html>
  <head></head>
  <body>
    <iframe srcdoc="&lt;html&gt;
  &lt;head&gt;
    &lt;base href=&quot;about:srcdoc&quot; /&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;div1&quot; style=&quot;height: 4000px&quot;&gt;
      First div
      &lt;a href=&quot;#div2&quot;&gt;Go to second div&lt;/a&gt;
    &lt;/div&gt;
    &lt;div id=&quot;div2&quot; style=&quot;height: 4000px&quot;&gt;
      Second div
      &lt;a href=&quot;#div1&quot;&gt;Go to first div&lt;/a&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;" style="width: 100%; height:10000px"></iframe>
  </body>
</html>

Is a page with that simple test document in an iframe using a srcdoc, with the base URL set to make anchors work as described above. If you save it as a .html file, load it in a browser, and click the links, the page will not scroll.

If you open a Developer console, navigate so you're running Javascript in the context of the iframe, and run window.location.hash, you'll see that the hash is being updated correctly. It's just that the page is not scrolling in response to that.

发布评论

评论列表(0)

  1. 暂无评论