带有 srcdoc 的 iframe:同页链接加载框架中的父页面

iframe with srcdoc: same-page links load the parent page in the frame

同一页 link 通过引用同一页上具有 id="sec-id" 的另一个元素来工作,使用

<a href="#sec-id"></a>

例如。这样的link是相对的

但是,如果我在 LaTeX.js playground 的 iframe 中使用完全相同的语法,它不仅会滚动到目标元素,还会(重新)加载 ifame 中的整个 playground 页面。 (请注意,我使用 iframe.srcdoc = html 以编程方式设置 iframe 的内容)

示例:LaTeX.js playground,在第一部分的末尾单击右侧 iframe 中 "See also Sec­tion 11." 中的 link。

可能是什么原因?

UPDATE:我现在明白了问题的根源:浏览器使用文档的基础 URL 使所有相对 URL 成为绝对的(见<base>). The trouble starts with an iframe that has its content set with srcdoc: no unique base URL is specified, and in that case the base URL of the parent frame/document is used--the playground in my case (see the HTML Standard).

因此,问题就变成了:有没有办法在基础 URL 中引用 srcdoc iframe?或者是否有可能让浏览器 前置基础?或者创建一个不改变相对 #sec-id URLs?

的基础 URL

我不知道你是如何解决这个问题的,我认为这是因为 srcdoc,你不能将 src 与内容类型一起使用,因为字符限制,但是您可以将它转换为 Blob 并且它有点管用,但是样式丢失了。也许您可以根据您的页面将其用作起点:

// Get the document content
const doc = document.querySelector('iframe').srcdoc;
// Convert it to blob
const blob = new Blob([doc], {type : 'text/html'});
// Load the blob on the src attr
document.querySelector('iframe').src = URL.createObjectURL(blob);
// Remove srcdoc to allow src
document.querySelector('iframe').removeAttribute('srcdoc');

郑重声明,我的问题似乎是不可能的,即,不可能在使用 srcdoc 设置内容的 iframe 中使用相对同页链接。必须使用解决方法,请参阅其他答案。

如何捕捉事件并滚动到所需的锚点?

$("a").click(function(e) {
    $('.iframe').animate({
       scrollTop: $(e.target.attr('href')).offset().top
    }, 2000);
    return false;
});