我目前正在为学校制作一个网站,我还很缺乏经验。
我遇到的问题是:
我的主页上有一个 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/