Javascript `base`tag使iframe在Internet Explorer中作为新窗口打开
我有一个问题,它只影响InternetExplorer(版本8、9和10) 下面的代码用于在iframe中打开动态内容,它在Chrome和Firefox中正常工作。它在Internet Explorer中也能正常工作,但只在没有Javascript `base`tag使iframe在Internet Explorer中作为新窗口打开,javascript,html,internet-explorer,iframe,Javascript,Html,Internet Explorer,Iframe,我有一个问题,它只影响InternetExplorer(版本8、9和10) 下面的代码用于在iframe中打开动态内容,它在Chrome和Firefox中正常工作。它在Internet Explorer中也能正常工作,但只在没有标记的情况下工作。包含此标记将导致iframe作为一个新窗口打开(这是有意义的,但是这不是我试图做的 <!DOCTYPE html> <html> <head> <meta http-equiv="Cont
标记的情况下工作。包含此标记将导致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>
功能加载框架(名称、高度、宽度){
var div=document.getElementById(名称);
var ifrm=document.createElement('iframe');
ifrm.id='iframe_u2;'+名称;
ifrm.frameBorder=0;
ifrm.scrolling='no';
ifrm.noresize='noresize';
ifrm.marginheight=0;
ifrm.marginwidth=0;
如果(高度!==0){
ifrm.height=高度;
}
如果(宽度!==0){
ifrm.width=宽度;
}
儿童分部(ifrm);
内容='';
if(/msie/.test(navigator.userAgent.toLowerCase())| | window.opera){
ifrm.contentWindow.contents=内容;
返回ifrm.src='javascript:window[“contents”];
}否则{
doc=ifrm.contentDocument;
doc.open();
文件编写(内容);
doc.close();
返回ifrm;
}
}
加载框架(“主”,250,300);
如何解决此问题?不幸的是,我无法使代码正常工作,可能是因为它依赖于
中的,我刚刚删除了/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);
我在chrome、IE8、IE11上进行了测试,效果非常好!如评论中所述,target=“\u blank”使浏览器打开一个新窗口或选项卡(取决于您的配置)
只需将其拆下或自行更换(在IE8上测试):
您是否尝试过给iframe一个值为“\u self”的“target”属性?是的,我尝试过。我认为target
不是iframediv=document.getElementById(div)的有效属性
和ifrm.id='iframe_u'+div;
没有意义,div
这里是一个HTMLElement,不是字符串。另外iframe
s没有noresize
属性,它是用于frame
s的。哇哦,是的,我已经修复了div
变量,这是错误的。@JoshuaSpence如果删除基本标记,iframe在Chrome和IE10/9/8中正常工作。“target=\u blank”的目的是在一个新窗口/选项卡中打开链接,因此如果您不想包含它。
<base target="_self"/>