admin管理员组

文章数量:1355675

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.

本文标签: htmlLinks to anchors within a document do not scroll the page with iframe using srcdocStack Overflow