小技巧,跨域关闭iframe

示例


解决方法

直接看代码吧:

function Dialog(){
	this.panel = document.createElement('div');
	this.panel.id = 'bmPanel';
	this.panel.style.position = 'absolute';
	this.panel.style.right = '0px';
	this.panel.style.right = this.scrollTop() + 'px';
	this.panel.style.zIndex = 100000;
	this.panel.style.margin = '10px';
	this.panel.style.width = '200px';
	this.panel.style.height = '200px';
	this.panel.style.border = '5px solid #CCC';
	this.panel.innerHTML = '<iframe id="bmIframe" '
		+ 'token="1" onload="c = this.getAttribute(\'token\'); if (c==3) {this.parentNode.parentNode.removeChild(this.parentNode)} this.setAttribute(\'token\',++c);"'
		+ 'name="bmIframe" src="main.html" scrolling="no" frameborder="0" style="width:100%; height:100%; '
		+ 'border:1px; padding:0px; margin:0px"></iframe>';
}

Dialog.prototype.show = function(){
	document.body.appendChild(this.panel);
}

Dialog.prototype.scrollTop = function (){
	return document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
}

注意iframe这一行:

onload="c = this.getAttribute(\'token\'); if (c==3) {this.parentNode.parentNode.removeChild(this.parentNode)} this.setAttribute(\'token\',++c);"

iframe里的关闭按钮链接一个简单的页面,通过不停地提交表单触发load事件,让token累加:

<body onload="document.getElementById('close').submit()">
	<form id="close" action="closeing.html" method="get"></form>
</body>

发表评论

Your email is never shared. Required fields are marked *

*
*