本文介绍在 JavaScript 中获取 iframe 内部元素值的兼容方法。针对 IE 与非 IE 浏览器(如 Firefox、Chrome)对 iframe 对象访问属性的差异,通过判断 document 属性是否存在来区分处理,分别使用 document.frames 或 contentWindow.document 获取子页面元素,实现跨浏览器取值功能。
iframe 取值兼容方案概述
本文通过具体实例,详细讲解利用 JavaScript 实现 iframe 框架内容取值的技术方案。
面对市面上众多浏览器导致的 JS/CSS 兼容性问题,开发者常感叹兼容工作的繁琐。虽然期望所有浏览器公司消失仅留一家是不切实际的幻想,但解决兼容性问题仍是开发中的必要环节。接下来通过代码展示具体实现方式。
iframe 框架内的页面结构如下:
iframe 内部页面结构
<html>
<head>
<title>框架内页</title>
</head>
<body>
<div>
<input id="txt1" name="txt1" type="text" value="测试" />
</div>
</body>
</html>
父级页面包含以下逻辑:
父级页面取值逻辑实现
<iframe name="frame1" id="frame1" src="frm.html" frameborder="1" height="30"></iframe>
<p>
iframe1中文本框的值:</p>
<p>
<input type="button" name="Submit" value="getValue" onclick="getValue()" />
</p>
<script type="text/javascript">
function getValue(){
var ofrm1 = document.getElementById("frame1").document;
if (ofrm1==undefined)
{
ofrm1 = document.getElementById("frame1").contentWindow.document;
var ff = ofrm1.getElementById("txt1").value;
alert("firefox/chrome取值结果为:" + ff);
}
else
{
var ie = document.frames["frame1"].document.getElementById("txt1").value;
alert("ie取值结果为:" + ie);
}
}
</script>
希望上述内容能为读者的 JavaScript 程序设计提供有益参考。