>  기사  >  웹 프론트엔드  >  html iframe 사용에 대한 실질적인 요약 공유

html iframe 사용에 대한 실질적인 요약 공유

黄舟
黄舟원래의
2017-07-21 11:32:393593검색

위에서 언급했듯이 iframe은 많은 일을 할 수 있습니다.
예:
a> iframe을 통해 교차 도메인 달성
b> IE6에서 선택이 차단될 수 없는 문제 해결
c> Ajax의 정방향 및 역방향 문제 해결
d> iframe을 통해. (Easyui의 양식 컴포넌트는 iframe을 사용합니다. 양식 제출 구현 시 업로드 도메인을 제출할 수 있습니다.)
아래에서 몇 가지 문제를 하나씩 논의하겠습니다.

1. iframe 기본 지식:

iframe 요소는 다른 문서를 포함하는 인라인 프레임(즉, 인라인 프레임)을 만듭니다.
HTML 4.1 Strict DTD 및 XHTML 1.0 Strict DTD에서는 iframe 요소가 지원되지 않습니다.
팁: iframe을 인식할 수 없는 브라우저를 처리하기 위해 d5ba1642137c3f32f4f4493ae923989c과 065276f04003e4622c4fe6b64f465b88 사이에 필요한 텍스트를 배치할 수 있습니다.

<iframe width=420 height=330 frameborder=0 scrolling=auto src="URL"></iframe>

선택 속성:

표준 속성:

2. iframe 작업:

   注:测试环境IE:8.0,FF:23.0.1
   a>隐藏iframe表框
		i>标签中设置:frameborder="0",<iframe frameborder="0" width="400" height="400" src="http://blog.csdn.net/cuew1987" scrolling="no"></iframe>
		ii>DOM操作:
			<body>
			<iframe frameborder="1" width="400" height="400" src="http://blog.csdn.net/cuew1987" scrolling="no" id="myiframe"></iframe>
			<script>
			var myiframe = document.getElementById("myiframe");
			myiframe.style.border="none";//FF下有效,IE下无效 
			myiframe.setAttribute("frameborder",0);//FF下有效,IE下无效 
			myiframe.frameBorder = 0;//FF下有效,IE下无效 
			</script>
			</body>
   b>动态创建iframe
   <script>
		var newFrame = document.createElement("iframe");
		newFrame.src ="http://blog.csdn.net/cuew1987";
		newFrame.frameBorder = 0;//FF、IE隐藏边框有效
		newFrame.width = "400px";
		newFrame.height = "400px";
		newFrame.scrolling = "no";
		document.body.appendChild(newFrame);
   </script>
   c>获取iframe
		i>var obj = document.getElementById("iframeID");
		  获取iframe对象,可直接操作iframe标签属性,如只想改变iframe的 src 或者 border ,scrolling 等attributes
		ii>var dom = frames["iframeName"];
		   获取iframe的DOM对象,此对象可用来操作对象,比如想操作iframe页面中的元素。
    d>获取iframe中的window对象
		function getIframeWindow(obj) {
			//IE || w3c
			return obj.contentWindow || obj.contentDocument.parentWindow;
			//parentWindow 是 parent window object
		}
		document.getElementById取到的iframe是不能直接操作里面的document的,只能这样取:
		IE:frames[id].document或obj.contentWindow.document;
		FF:dom.contentDocument或obj.contentDocument;不绑定任何事件.
	e>获取iframe页面高度
		function getIframeHeight(obj){
			var idoc = getIframeWindow(obj).document; 
			if(idoc.body){
				return Math.max(idoc.body.scrollHeight,idoc.body.offsetHeight);   
			}else if(idoc.documentElement){
				return Math.max(idoc.documentElement.scrollHeight,idoc.documentElement.offsetHeight);   
			}
		}
	f>父子页面互访
		i>子访问父:
			parent.html:
			<body>
				<p>等到的信息:<p id="msg"></p></p>
				<iframe frameborder="1" width="400" height="400" src="son.html" scrolling="no" id="myiframe"></iframe>
			</body>
			son.html:
			<body>
			<input type="button" onClick="setMsg()" value="setMsg">
			<script>
			function setMsg(){
				var msg = window.parent.document.getElementById("msg");
				msg.innerHTML= "Hello world!!";
			}
			</script>
			</body>
		ii>父访问子:
			parent.html:
			<body>
			<p>等到的信息:<p id="setMsg"></p></p>
			<input type="button" value="setMsg" onClick="setMsg()"><br>
			<iframe frameborder="1" width="400" height="400" src="son.html" scrolling="no" id="myiframe"></iframe>
			<script type="text/javascript">
			function setMsg(){
				var obj = document.getElementById("myiframe");
				var msg = getIframeWindow(obj).document.getElementById("msg");
				document.getElementById("setMsg").innerHTML = msg.innerHTML;
			}
			</script>
			</body>
			son.html:
			<body>
			<p id="msg">Hello world!!!</p>
			</body>


3.iframe 고도로 적응력이 뛰어나고 도메인 간:

实际使用iframe中,会遇到iframe高度的问题,由于被嵌套的页面长度不固定而显示出来的滚动条,不仅影响美观,还会对用户操作带来不便
	a>同域下的高度自适应
	parent.html:
	<body>
	<iframe width="400" id="myiframe" onload="setHeight()" height="1" frameborder="0" src="son.html"></iframe>
	<script type="text/javascript">  
	function getIframeWindow(obj) {
		return obj.contentWindow || obj.contentDocument.parentWindow;
	}
	function getIframeHeight(obj){
		var idoc = getIframeWindow(obj).document; 
		if(idoc.body){
			return Math.max(idoc.body.scrollHeight,idoc.body.offsetHeight);   
		}else if(idoc.documentElement){
			return Math.max(idoc.documentElement.scrollHeight,idoc.documentElement.offsetHeight);   
		}
	}
	function setHeight(){   
		var myiframe = document.getElementById("myiframe");
		myiframe.height = getIframeHeight(myiframe);
	} 
	</script> 
	</body>
	另:document.documentElement与document.body相关说明(W3C DOM2.0规范)
	document.doucmentElement:
		documentElement of type Element, readonly,This is a convenience attribute that allows direct access to the 
		child node that is the root element of the document. For HTML documents, this is the element with the tagName "HTML".
	document.body:
		document.body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, 
		and in frameset documents, this returns the outermost <frameset> element.
		Though body is settable, setting a new body on a document will effectively remove all the current children of the existing <body> element.
	IE在怪异模型(Quicks Mode)下document.documentElement无法正确取到clietHeight scrollHeight等值,比如clientHeight=0。
	获取scrollTop:
	var sTop=Math.max(
		(document.body?document.body.scrollTop:0),
		(document.documentElement?document.documentElement.scrollTop:0),
		(window.pageYOffset?window.pageYOffset:0)
	);    

	b>跨域下高度自适应
	页面:
	index.html:(http://www.csdn.net)
	<iframe width="400" id="myiframe" onload="setHeight()" height="1" frameborder="0" src="son.html"></iframe>
	son.html:
	<body >
	<iframe id="agentIframe" style="position:absolute; top:-10000;left:-1000;" height="10" width="100%"></iframe>
	</body>
	<script>
		function getHeight(){
			var idoc = document; 
			if(idoc.body){
				return Math.max(idoc.body.scrollHeight,idoc.body.offsetHeight);   
			}else if(idoc.documentElement){
				return Math.max(idoc.documentElement.scrollHeight,idoc.documentElement.offsetHeight);   
			}
		}
		window.onload = function(){
			var h = getHeight();
			document.getElementById("agentIframe").src="http://www.csdn.net#"+h;
		}
	</script>
	agent.html:(http://www.csdn.net)
	<script>
	(function(){
		var con = parent.parent.document.getElementById(&#39;frame_content&#39;);     
		var href = parent.parent.frames["frame_content"].frames["iframeC"].location.hash;      
		con.style.height = href.split("#")[1]+"px";
	})();
	</script>

4 .iframe 배경 투명:

ie6/7/8에 iframe이 도입되면 기본적으로 style="backup-color:transparent;"가 설정되어 있어도 유효하지 않습니다.
다른 브라우저(firefox, chrome, Opera, ie9) 이 호환성 문제를 해결하려면 속성을 사용해야 합니다.
현상을 살펴보겠습니다.

index.html:
<body style="background-color:#00f;">
<iframe frameborder="0" height="200" width="200"  src="son.html" scrolling="yes" id="myiframe" 
style="background-color:transparent;"></iframe>
</body>


결과는 아래와 같습니다. (index.html에 스크롤 막대가 설정되어 있으므로 FF에 스크롤 막대가 있습니다.)

해결책:
iframe 속성 설정: allowTransparency="true" //투명성을 허용하려면 true로 설정

<body style="background-color:#00f;">
<iframe allowTransparency="true" frameborder="0" height="200" width="200"  src="son.html" 
scrolling="yes" id="myiframe"></iframe>
</body>


참고: iframe이 이 속성을 설정하지 않은 경우 iframe을 사용하여 IE6 및 7 환경에서 선택 항목을 다루는 문제를 해결할 수 있습니다

5. 페이지에 iframe이 있습니다:

	a>首先来看看window.frameElement这个属性。
		返回嵌入当前window对象的元素(比如 <iframe> 或者 <object>),即为包含本页面的iframe或frame对象。如果当前window对象已经是顶层窗口,则返回null.
		看看一个例子:
		parent.html:
		<body>
		<iframe frameborder="1" width="400" height="400" src="son.html" scrolling="no" id="myiframe"></iframe>
		</body>
		son.html:(注意frameElement用在son.html中,如果用在parent.html中,则返回null)
		<body>
		<p id="msg">Hello world!!!</p>
		<script type="text/javascript">
			var iframe = window.frameElement;
			if(iframe){
				iframe.src = "http://blog.csdn.net/cuew1987";
			}
		</script>
		</body>
		备注:虽然该属性名为frameElement,但该属性也会返回其他类型比如 <object> 或者其他可嵌入窗口的元素.
	b>兼容性如下图:


	c>定义函数:
		i>判断父页面中是否含有iframe
		function hasIframe(){
			return document.getElementsByTagName("iframe").length > 0;
		}
		ii>判断某个页面是否在iframe标签中
		function innerIframe(){
			var iframe = window.frameElement;
			if(iframe){
				return typeof iframe !== "undefined";
			}
		}

6. HTML5의 iframe:

HTML 4.01과 HTML 5의 차이점. HTML 5에서는 src 속성만 지원됩니다
5c9a977fc25d2aa89902ba4e6a840e41065276f04003e4622c4fe6b64f465b88
HTML5의 전역 속성:

7. easyui의 양식 구성 요소 제출(업로드 도메인 포함):

	function submitForm(target, options) {
		options = options || {};
		if (options.onSubmit) {
			if (options.onSubmit.call(target) == false) {
				return;
			}
		}
		var form = $(target);
		if (options.url) {
			form.attr("action", options.url);
		}
		var frameId = "easyui_frame_" + (new Date().getTime());
		var frame = $("<iframe id=" + frameId + " name=" + frameId + "></iframe>").attr(
				"src",
				window.ActiveXObject ? "javascript:false" : "about:blank").css(
				{
					position : "absolute",
					top : -1000,
					left : -1000
				});
		var t = form.attr("target"), a = form.attr("action");
		form.attr("target", frameId);//在iframe中提交表单
		try {
			frame.appendTo("body");
			frame.bind("load", cb);
			form[0].submit();
		} finally {
			form.attr("action", a);
			t ? form.attr("target", t) : form.removeAttr("target");
		}
		var checkCount = 10;
		function cb() {
			frame.unbind();
			var body = $("#" + frameId).contents().find("body");
			//contents()查找匹配元素内部所有的子节点(包括文本节点)。如果元素是一个iframe,则查找文档内容
			var data = body.html();
			if (data == "") {
				if (--checkCount) {
					setTimeout(cb, 100);
					return;
				}
				return;
			}
			var ta = body.find(">textarea");
			if (ta.length) {
				data = ta.val();
			} else {
				var pre = body.find(">pre");
				if (pre.length) {
					data = pre.html();
				}
			}
			if (options.success) {
				options.success(data);
			}
			setTimeout(function() {
				frame.unbind();
				frame.remove();
			}, 100);
		};
	};
	另:form 的target属性:
	a>HTML4中:
	定义和用法:target 属性规定在何处打开 action URL。
	兼容性:在 HTML 4.01 中,不赞成使用 form 元素的 target 属性;在 XHTML 1.0 Strict DTD 中,不支持该属性。
	属性值:
	_blank 新窗口中打开
	_self  默认,在相同的框架中打开
	_parent 父框架中打开
	_top    整个窗口中打开
	framename  指定的frame name属性值的框架中打开

	b>HTML5中:
	HTML 4.01 与 HTML 5 之间的差异
	在 HTML5 中 target 属性不再是被废弃的属性。不再支持 frame 和 frameset。
	现在,parent, top 和 framename 值大多用于 iframe。

8. 온라인 문제 컬렉션:

a>window .frameElement가 Chrome에서 정의되지 않았나요?

문제 설명:
오늘 캘린더 구성요소를 다시 작성할 때 iframe 사용자 정의 속성을 사용하여 값을 전달했기 때문에
iframe 사용자 정의 속성에 상위 페이지의 값을 쓴 다음 다음을 사용합니다. window.frameElement.getAttribute()를 iframe 페이지에서 얻으려면,
이상한 점은 이전에 작성한 캘린더 제어 코드는 항상 이렇게 작성해 오류가 발생하지 않았는데 오늘 크롬에서는 window.frameElement가 나왔던 것입니다. 정의되지 않음,
firefox나 심지어 IE6에서도 문제가 없는데 Baidu에서는 답변이 없고 google에서도 답변이 없습니다.
해결책:
마지막으로, 지난 경험을 바탕으로 로컬 디버깅 권한에 문제가 있을 수 있다고 생각하여 아파치를 열고 도메인 이름을 사용하여 액세스했습니다. 물론 작동했습니다. 하하!

위 내용은 html iframe 사용에 대한 실질적인 요약 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.