问题描述
如果您知道iframe的ID,如何在页面上选择iframe DOM对象?假设页面上可能有多个iframe,并且您不知道相关问题的位置,也请不要使用jQuery解决方案。我想出了以下内容,但是,我希望它可以更加轻松。
How do you select the iframe DOM Object on the page if you know the iframe's ID? Assume there might be multiple iframes on the page and you don't know the position of the one in question, and also no jQuery solutions please. I came up with the following, however, I expect it can be much more trivial.
编辑。我正在尝试获取DOM对象,以便我可以访问属性,例如 window.frames [0] .innerHeight
EDIT. I am trying to get the DOM object, so that I can access properties such as window.frames[0].innerHeight
function getIframe(id) {
var iframe=null;
for (var i = window.frames.length - 1; i >= 0; i--) {
if(window.frames[i].frameElement.id==id){iframe=window.frames[i];break;}
}
return iframe;
}
推荐答案
看到这个答案:
window.frames['myIFrame']
编辑:
我对FF和Chrome进行了一些测试,得出以下结论。
I made some tests on FF and Chrome and came up with the following conclusions.
window.frames [myFrame]
返回:
`[object HTMLIFrameElement]` when on FF (v24)
`[object Window]` when on Chrome (v 30.0.1599.101)
我们可以为 HTMLIFrameElement
属性<$ c $制作这样的控件c> contentWindow 获取iframe 窗口
:
we can make a control like this for HTMLIFrameElement
property contentWindow
to get the iframe Window
:
var myFrame = (window.frames["myFrame"].contentWindow ? window.frames["myFrame"].contentWindow : window.frames["myFrame"])
这种方式在变量myFrame中存储了 Window
对象。
This way in the variable myFrame is stored the Window
object.
如果现在我们想要获取DOM元素 HTMLIFrameElement
,我们可以这样做:
If now we want to get the DOM element HTMLIFrameElement
we can simply do:
var domElement = myFrame.frameElement
希望这会有用。
这篇关于获取给定ID的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!