javascript - 从 iframe 本身内的另一个页面延长 iframe

标签 javascript html iframe

我目前正在为学校制作一个网站,我还很缺乏经验。
我遇到的问题是:

我的主页上有一个 iframe,我想根据单击的链接使其更长。
这部分很简单,但不简单的是,当点击 iframe 内的链接时,iframe 会变长。

所以我有一个外部脚本,我可以在其中执行

function getObj(name)
{
  if (document.getElementById)
  {
    this.obj = document.getElementById(name);
    this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
    this.obj = document.all[name];
    this.style = document.all[name].style;
  }
  else if (document.layers)
  {
    this.obj = document.layers[name];
    this.style = document.layers[name];
  }
}

var frame, div1;  
function mainInit(){
  frame = new getObj("idFrame");
}

function init2(){
     div1 = new getObj("divWithTable");
     div1.style.visibility = "hidden";
}

function ShowDiv(){
  div1.style.visibility = "visible";
  //frame.obj.height = 1000;
}

所以我有一个<body onload="mainInit()">在我的主页上和一个 <body onload="init2()">在 iframe 内的页面上,其中还有一个带有 onclick="ShowDiv()" 的按钮.

现在的问题是:
当我单击在其中页面上显示 div 的按钮时,我无法更改 iframe 的长度。我需要以某种方式从第一页返回定义的 iframe,以便我可以在第二页上使用它。

最佳答案

如果您位于同一来源,您应该能够访问链接并向其附加函数。 :)

// Find the iframe (in this case by it's tag <iframe>)
var iframe = document.getElementsByTagName('iframe')[0];
// Get the content of the iframe
// The || means or, this is to account for the way different browser allow access to iframe content
// If you cant get the contentDocument, then it'll give you the contentWindow.document 
var iframeContent = iframe.contentDocument || iframe.contentWindow.document;

// Finally we get the link elements from the iframe
// In this example all of our links have the class 'my-link', but you could get by tag name <a> (in the same way we got the iframe)
var iframeLinks = iframeContent.getElementsByClassName('my-link');

// Then add your listeners to the links

如果您在本地运行它,您将需要一个虚拟服务器。有很多非常容易运行的东西。 :)

关于javascript - 从 iframe 本身内的另一个页面延长 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858219/

相关文章:

javascript - 从 iframe 更改文本区域值

javascript - 如何在 JavaScript 中列出所有数组?

javascript - 通过ajax(chrome)在vanilla js中以编程方式触发文件输入点击

jquery - 使用 jQuery 阻止 iFrame 内的 F5

javascript - 根据条件注释/取消注释代码

javascript - 为什么我的 C# 函数不从 ajax Javascript 代码执行?

html - 如何将表格标题与表格内容对齐?

javascript - 隐藏选择字段中的额外数据?

javascript - 如何在 iFrame 中加载 PDF 文件?在 react 中工作

javascript - 从嵌套在 Javascript 中的 iframe 标签中删除垂直滚动条