乐闻世界logo
搜索文章和话题

Iframe 如何强制在父窗口中打开链接?

6 个月前提问
3 个月前修改
浏览次数144

6个答案

1
2
3
4
5
6

在使用 iframe 的时候,通常情况下,链接默认会在该 iframe 内打开。如果想要强制链接在父窗口中打开,可以通过几种方法实现:

  1. 使用 HTML 的 target 属性:iframe 内的链接上设置 target="_parent" 属性,可以使该链接在父窗口中打开。这是标准的HTML方法,兼容性良好。

    例如:

    html
    <a href="http://www.example.com" target="_parent">Open in Parent Window</a>
  2. 使用 JavaScript: 通过编写 JavaScript 代码,可以监听 iframe 内部的链接点击事件,并强制它们在父窗口中打开。

    例如:

    javascript
    // 假设你有一个ID为"myIframe"的iframe var iframe = document.getElementById('myIframe'); // 下面的代码会为iframe内的所有链接绑定点击事件 // 当点击时,链接将在父窗口中打开 iframe.contentWindow.document.body.addEventListener('click', function(e) { var target = e.target; if(target.tagName === 'A') { e.preventDefault(); parent.location.href = target.href; } });
  3. 使用 base 标签:iframehead 部分中添加一个 base 标签,并设置 target="_parent" 也能达到相同的效果。

    例如,在 iframe 的文档中:

    html
    <head> <base target="_parent"> </head>

    这样,iframe 中的所有链接默认都会在父窗口中打开。

以上就是主要的几种方法,你可以根据具体的应用场景和需求来选择最适合的方案。

2024年6月29日 12:07 回复

我发现最好的解决方案是使用基本标签。将以下内容添加到 iframe 中页面的头部:

shell
<base target="_parent">

这将加载父窗口中页面上的所有链接。如果您希望链接在新窗口中加载,请使用:

shell
<base target="_blank">

浏览器支持

2024年6月29日 12:07 回复

使用目标属性:

shell
<a target="_parent" href="http://url.org">link</a>
2024年6月29日 12:07 回复

使用 JavaScript:

shell
window.parent.location.href= "http://www.google.com";
2024年6月29日 12:07 回复

您可以使用任何选项

如果只有父页面:

如果您想打开父页面或父 iframe的所有链接,请在 iframe 的 head 部分使用以下代码:

<base target="_parent" />

或者

如果您想打开父页面或父 iframe 的特定链接,请使用以下方式:

shell
<a target="_parent" href="http://specific.org">specific Link</a> <a href="http://normal.org">Normal Link</a>

或者

如果是嵌套 iframe:

如果想打开浏览器窗口中的所有链接(在浏览器 URL 中重定向),则可以在 iframe 的 head 部分使用以下代码:

shell
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> $(window).load(function(){ $("a").click(function(){ top.window.location.href=$(this).attr("href"); return true; }) }) </script>

或者

如果您想在浏览器窗口中打开特定链接(在浏览器 URL 中重定向),则可以使用以下方式:

shell
<a href="http://specific.org" target="_top" >specific Link</a>

或者

shell
<a href="javascript:top.window.location.href='your_link'">specific Link</a> <a href="javascript:top.window.location.href='http://specific.org'">specific Link</a> <a href="http://normal.org">Normal Link</a>
2024年6月29日 12:07 回复

有一个名为的 HTML 元素base,它允许您:

为页面上的所有链接指定默认 URL 和默认目标:

shell
<base target="_blank" />

通过指定,_blank您可以确保_iframe_内的所有链接都将在外部打开。

2024年6月29日 12:07 回复

你的答案