Jos*_*nce 6 html javascript iframe internet-explorer
我的base标签有问题,只影响Internet Explorer(版本8,9和10).
以下代码用于在iframe中打开动态内容,并且它在Chrome和Firefox中正常运行.它也可以在Internet Explorer中正常运行,但只能没有<base target="_blank"/>标记.包含此标记会导致iframe作为新窗口打开(这是有道理的,但这不是我想要做的.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<base target="_blank"/>
</head>
<body>
<div id="main"></div>
<script type="text/javascript">
function load_iframe(name, height, width) {
var div = document.getElementById(name);
var ifrm = document.createElement('iframe');
ifrm.id = 'iframe_' + name;
ifrm.frameBorder = 0;
ifrm.scrolling = 'no';
ifrm.noresize = 'noresize';
ifrm.marginheight = 0;
ifrm.marginwidth = 0;
if (height !== 0) {
ifrm.height = height;
}
if (width !== 0) {
ifrm.width = width;
}
div.appendChild(ifrm);
content = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head></head><body></body></html>';
if (/msie/.test(navigator.userAgent.toLowerCase()) || window.opera) {
ifrm.contentWindow.contents = content;
return ifrm.src = 'javascript:window["contents"]';
} else {
doc = ifrm.contentDocument;
doc.open();
doc.write(content);
doc.close();
return ifrm;
}
}
load_iframe('main', 250, 300);
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?不幸的是,我无法让代码在小提琴中工作,也许是因为它依赖于<base/>存在<head>.
我刚刚删除了该/msie/.test(navigator.userAgent.toLowerCase()) ||部分,并且在 IE8 上运行良好。您确定需要这段代码吗?
但是,无论您不想删除这一部分,都可以删除该标签并在创建后base添加它:iframe
load_iframe('main', 250, 300);
//and then:
var hd = document.getElementsByTagName("head")[0];
var bs = document.createElement("base");
bs.target= "_blank";
hd.appendChild(bs);
Run Code Online (Sandbox Code Playgroud)
我在 chrome、IE8、IE11 上测试过,完美运行!