조정의 너비와 높이 iframe 에 맞게 컨텐츠에
-
03-07-2019 - |
문제
나는에 대한 솔루션이 필요 자동 조정 이 width
고 height
의 iframe
을 거의 내용에 맞게 조정됩니다.점은 폭과 높이 변경 될 수 있습 후 iframe
니다.난 필요한 이벤트 조치와 거래에서 변경 차원의 몸에 포함된다.
해결책
<script type="application/javascript">
function resizeIFrameToFitContent( iFrame ) {
iFrame.width = iFrame.contentWindow.document.body.scrollWidth;
iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}
window.addEventListener('DOMContentLoaded', function(e) {
var iFrame = document.getElementById( 'iFrame1' );
resizeIFrameToFitContent( iFrame );
// or, to resize all iframes:
var iframes = document.querySelectorAll("iframe");
for( var i = 0; i < iframes.length; i++) {
resizeIFrameToFitContent( iframes[i] );
}
} );
</script>
<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>
다른 팁
크로스 브라우저 jQuery 플러그인.
크로스 봇, 크로스 도메인 도서관 그것은 사용합니다 mutationObserver
Iframe 크기를 컨텐츠에 크기로 유지합니다 postMessage
iframe과 호스트 페이지를 통신합니다. jQuery와 함께 사용됩니다.
지금까지 주어진 모든 솔루션은 한 번만 해제 된 크기를 설명합니다. 내용이 수정 된 후 iframe을 크기를 조정할 수 있기를 원한다고 말합니다. 이렇게하려면 iframe 내부에서 함수를 실행해야합니다 (내용이 변경되면 내용이 변경되었다고 말하면 이벤트를 발사해야합니다).
iframe 내부의 코드가 iframe 내부의 DOM으로 제한된 것처럼 보였고 (Iframe을 편집 할 수 없었고) Iframe 외부에서 실행 된 코드는 iframe 외부의 Dom에 붙어 있었다 (그리고 할 수 있었다. t Iframe 내부에서 나오는 이벤트를 선택하십시오).
이 솔루션은 jQuery가 어떤 DOM을 사용할 것인지 알 수 있다는 것을 발견 한 (동료의 지원을 통해) 발견에서 비롯되었습니다. 이 경우 부모 창의 DOM.
따라서 이와 같은 코드는 필요한 작업을 수행합니다 (IFRAME 내부에서 실행할 때) :
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#IDofControlFiringResizeEvent").click(function () {
var frame = $('#IDofiframeInMainWindow', window.parent.document);
var height = jQuery("#IDofContainerInsideiFrame").height();
frame.height(height + 15);
});
});
</script>
iframe 컨텐츠가 동일한 도메인에서 나온 경우 이것이 효과적입니다. 그래도 jQuery가 필요합니다.
$('#iframe_id').load(function () {
$(this).height($(this).contents().height());
$(this).width($(this).contents().width());
});
동적으로 크기를 조정하려면 다음을 수행 할 수 있습니다.
<script language="javaScript">
<!--
function autoResize(){
$('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>
그런 다음 iframe로드가있는 페이지에서 다음을 추가합니다.
<script language="javaScript">
function resize()
{
window.parent.autoResize();
}
$(window).on('resize', resize);
</script>
하이너에 대한 솔루션을 포함:시작으로 분 크기와 증가하는 컨텐츠 크기입니다.필요 없음에 대한 스크립트 태그.
<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
jQuery를 사용하고 싶지 않은 경우 크로스 브라우저 솔루션은 다음과 같습니다.
/**
* Resizes the given iFrame width so it fits its content
* @param e The iframe to resize
*/
function resizeIframeWidth(e){
// Set width of iframe according to its content
if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
e.width = e.contentWindow.document.body.scrollWidth;
else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
e.width = e.contentDocument.body.scrollWidth + 35;
else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
e.width = e.contentDocument.body.offsetWidth + 35;
}
이 코드를 사용하여 페이지에로드 할 때 모든 iframes (클래스 자동 사용자)의 높이를 자동 조정하고 있습니다. 테스트 및 IE, FF, Chrome, Safari 및 Opera에서 작동합니다.
function doIframe() {
var $iframes = $("iframe.autoHeight");
$iframes.each(function() {
var iframe = this;
$(iframe).load(function() {
setHeight(iframe);
});
});
}
function setHeight(e) {
e.height = e.contentWindow.document.body.scrollHeight + 35;
}
$(window).load(function() {
doIframe();
});
지구상의 모든 것을 시도한 후에는 이것이 실제로 저에게 효과적입니다.
index.html
<style type="text/css">
html, body{
width:100%;
height:100%;
overflow:hidden;
margin:0px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>
이것은 확실한 증거 솔루션입니다
function resizer(id)
{
var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;
var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
document.getElementById(id).style.height=height;
document.getElementById(id).style.width=width;
}
HTML
<IFRAME SRC="blah.php" id="iframe1" onLoad="resizer('iframe1');"></iframe>
나는 위의 Garnaph의 훌륭한 솔루션을 약간 수정했습니다. 그의 솔루션이 이벤트 직전의 크기에 따라 iframe 크기를 수정 한 것처럼 보였습니다. 내 상황 (iframe을 통한 이메일 제출)의 경우 제출 직후에 Iframe 높이가 변경되어야했습니다. 예를 들어 제출 후 유효성 검사 오류 또는 "감사합니다"메시지를 표시합니다.
방금 중첩 된 Click () 함수를 제거하고 Iframe HTML에 넣었습니다.
<script type="text/javascript">
jQuery(document).ready(function () {
var frame = $('#IDofiframeInMainWindow', window.parent.document);
var height = jQuery("#IDofContainerInsideiFrame").height();
frame.height(height + 15);
});
</script>
저를 위해 일했지만 크로스 브라우저 기능에 대해서는 확실하지 않습니다.
몇 가지 방법은 다음과 같습니다.
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>
그리고 또 다른 대안
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>
위와 같이 두 개의 대안으로 스크롤을 숨기려면
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>
두 번째 코드로 해킹
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>
iframe의 스크롤 바를 숨기려면 부모는 "오버플로 : 숨겨진"스크롤 바를 숨기려고 "오버플로 : 숨겨진"과 IFRAME는 150%의 너비와 높이로 이동하여 페이지 외부의 스크롤 바를 강제하고 신체가 방해가되지 않기 때문에 '' t 스크롤 바가 iframe이 페이지의 한계를 초과 할 것으로 기대하지 않을 수 있습니다. 이것은 전체 너비로 iframe의 스크롤 바를 숨 깁니다!
출처 : 세트 Iframe 자동 높이
모두 위의 방법을 사용하여 작동 할 수 없습니다.
자바 스크립트 :
function resizer(id) {
var doc = document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;
var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);
document.getElementById(id).style.height = height;
document.getElementById(id).style.width = width;
}
HTML :
<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv" >
<input id="txtHeight"/>height <input id="txtWidth"/>width
<iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0" ></iframe>
<iframe src="left.aspx" name="leftFrame" scrolling="yes" id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
<iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; " onload="resizer('Iframe2');" ></iframe>
</div>
ENV : IE 10, Windows 7 x64
iframe 컨텐츠와 부모 창을 모두 제어 할 수 있다면 iframe resizer.
이 라이브러리를 사용하면 동일 및 크로스 도메인 IFRAME의 높이와 너비의 자동 크기 조정이 포함 된 컨텐츠에 맞도록 할 수 있습니다. iframes 사용과 관련하여 가장 일반적인 문제를 해결하기위한 다양한 기능을 제공합니다. 여기에는 다음이 포함됩니다.
- Iframe의 컨텐츠 크기에 대한 높이 및 너비 크기 조정.
- 다중 및 중첩 iframes와 함께 작동합니다.
- 크로스 도메인 iframes에 대한 도메인 인증.
- 복잡한 CSS 레이아웃을 지원하기위한 다양한 페이지 크기 계산 방법을 제공합니다.
- MutationObserver를 사용하여 페이지가 크기를 조정할 수있는 DOM의 변경 사항을 감지합니다.
- 페이지가 크기를 조정할 수있는 이벤트를 감지합니다 (창 크기, CSS 애니메이션 및 전환, 오리엔테이션 변경 및 마우스 이벤트).
- PostMessage를 통해 iframe과 호스트 페이지 간의 단순화 된 메시지.
- iframe의 페이지 링크의 수정 및 iframe과 부모 페이지 간의 링크를 지원합니다.
- 맞춤형 크기 조정 및 스크롤 방법을 제공합니다.
- 부모 위치와 뷰포트 크기를 IFRAME에 노출시킵니다.
- PDF 및 ODF 문서를 지원하기 위해 ViewerJS와 협력합니다.
- 폴백 지원은 IE8로입니다.
누군가가 여기에 도착하는 경우 : iframe에서 divs를 제거했을 때 솔루션에 문제가있었습니다. Iframe은 짧아지지 않았습니다.
작업을 수행하는 jQuery 플러그인이 있습니다.
http://www.jqueryscript.net/layout/jquery-plugin-for-auto-resizing-iframe-frame-resizer.html
실험 후 다른 해결책을 알아 냈습니다. 나는 원래이 질문에 '베스트 답변'으로 표시된 코드를 시도했지만 작동하지 않았습니다. 내 추측은 당시 내 프로그램의 Iframe이 동적으로 생성 되었기 때문입니다. 다음은 내가 사용한 코드입니다 (저를 위해 작동했습니다).
로드중인 iframe 내부의 JavaScript :
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
스크롤 막대 (IFRAMES의 이상한 버그/효과)를 제거하려면 높이에 4 개 이상의 픽셀을 추가해야합니다. 너비는 심지어 낯선 사람이며 몸의 너비에 18px를 추가하는 것이 안전합니다. 또한 Iframe 본문에 대한 CSS가 적용되었는지 확인하십시오 (아래).
html, body {
margin:0;
padding:0;
display:table;
}
iframe {
border:0;
padding:0;
margin:0;
}
iframe의 HTML은 다음과 같습니다.
<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>
다음은 내 iframe 내의 모든 코드입니다.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>File Upload</title>
<style type="text/css">
html, body {
margin:0;
padding:0;
display:table;
}
</style>
<script type="text/javascript">
window.onload = function()
{
parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
};
</script>
</head>
<body>
This is a test.<br>
testing
</body>
</html>
Chrome에서 테스트를 수행했으며 Firefox (Windows XP)에서 약간의 테스트를 수행했습니다. 나는 여전히 더 많은 테스트를 할 수 있으므로 이것이 당신에게 어떻게 작동하는지 알려주세요.
이 레기 라이저가 더 잘 작동하는 것을 발견했습니다.
function resizer(id)
{
var doc = document.getElementById(id).contentWindow.document;
var body_ = doc.body;
var html_ = doc.documentElement;
var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );
document.getElementById(id).height = height;
document.getElementById(id).width = width;
}
참고 스타일 객체가 제거됩니다.
jQuery에서 이것은 나에게 최선의 선택입니다. 정말 도움이됩니다 !! 나는 당신을 도와줍니다!
Iframe
<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>
jQuery
<script>
var valueSize = $( "#iframe" ).offset();
var totalsize = (valueSize.top * 2) + valueSize.left;
$( "#iframe" ).height(totalsize);
</script>
거기에 없었던 것처럼 행동하는 "유령 같은"iframe을 만들 수 있습니다.
보다 http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/
기본적으로 이벤트 시스템을 사용합니다 parent.postMessage(..)
설명합니다https://developer.mozilla.org/en-us/docs/dom/window.postmessage
이것은 모든 현대식 브라우저로 작동합니다!
이것이 내가하는 방법입니다 (FF/Chrome에서 테스트) :
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>
나는 게시물이 늙었다는 것을 알고 있지만, 이것이 또 다른 방법이라고 생각합니다. 방금 내 코드를 구현했습니다. 페이지로드와 페이지 크기 조정 모두에서 완벽하게 작동합니다.
var videoHeight;
var videoWidth;
var iframeHeight;
var iframeWidth;
function resizeIframe(){
videoHeight = $('.video-container').height();//iframe parent div's height
videoWidth = $('.video-container').width();//iframe parent div's width
iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
}
resizeIframe();
$(window).on('resize', function(){
resizeIframe();
});
헤더에 배치 할 JavaScript :
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
다음은 iframe html 코드를 사용합니다.
<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>
CSS 스타일 시트
>
.spec_iframe {
width: 100%;
overflow: hidden;
}
AngularJS 지침 속성의 경우 :
G.directive ( 'previewIframe', function () {
return {
restrict : 'A',
replace : true,
scope : true,
link : function ( scope, elem, attrs ) {
elem.on ( 'load', function ( e ) {
var currentH = this.contentWindow.document.body.scrollHeight;
this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
} );
}
};
} );
비율에 주목하십시오. 나는 당신이 일반적으로 iframe, 텍스트, 광고 등에 대해 스케일링에 대응할 수 있도록 삽입했습니다. 스케일링이 구현되지 않으면 0을 넣습니다.
내용이 매우 간단한 HTML 인 경우 가장 간단한 방법은 JavaScript로 iframe을 제거하는 것입니다.
HTML :
<div class="iframe">
<iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>
자바 스크립트 :
function removeIframe(obj)(
var iframeDocument = obj.contentDocument || obj.contentWindow.document;
var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
obj.remove();
document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}
이것이 내가 onload 또는 일이 바뀌는 방식입니다.
parent.jQuery("#frame").height(document.body.scrollHeight+50);
문맥
나는 웹 확장의 맥락에서 이것을 직접해야했다. 이 웹 확장은 각 페이지에 일부 UI 조각을 주입 하고이 UI는 iframe
. 내부의 내용 iframe
역동적이므로 너비와 높이를 재조정해야했습니다. iframe
그 자체.
나는 사용한다 반응 그러나 개념은 모든 라이브러리에 적용됩니다.
내 솔루션 (이것은 페이지와 iframe을 모두 제어한다고 가정합니다)
내부 iframe
나는 바뀌었다 body
정말 큰 차원을 갖는 스타일. 이를 통해 필요한 모든 공간을 사용하여 내부의 요소가 배치 될 수 있습니다. 만들기 width
그리고 height
100%는 나에게 효과가 없었습니다 (iframe에 기본값이 있기 때문에 width = 300px
그리고 height = 150px
)
/* something like this */
body {
width: 99999px;
height: 99999px;
}
그런 다음 나는 div 내부의 모든 iframe ui를 주입하고 몇 가지 스타일을 주었다.
#ui-root {
display: 'inline-block';
}
내 앱을 이것 안에 렌더링 한 후 #ui-root
(안에 반응 나는 이것을 내부에서한다 componentDidMount
) 나는이 div와 같은 크기를 계산하고 그것들을 사용하여 부모 페이지에 동기화합니다. window.postMessage
:
let elRect = el.getBoundingClientRect()
window.parent.postMessage({
type: 'resize-iframe',
payload: {
width: elRect.width,
height: elRect.height
}
}, '*')
부모 프레임에서 나는 다음과 같은 일을한다.
window.addEventListener('message', (ev) => {
if(ev.data.type && ev.data.type === 'resize-iframe') {
iframe.style.width = ev.data.payload.width + 'px'
iframe.style.height = ev.data.payload.height + 'px'
}
}, false)
분명히 많은 시나리오가 있지만 문서와 iframe에 대한 동일한 도메인을 가지고 있었고 iframe 컨텐츠의 끝까지이를 해결할 수있었습니다.
var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';
이것은 부모 컨테이너를 '찾은 다음'스크롤 막대를 제거하기 위해 50 픽셀의 퍼지 팩터를 추가하는 길이를 설정합니다.
문서 높이 변경을 '관찰'할 수있는 것은 없습니다. 이것은 제 사용 사례에 필요하지 않았습니다. 내 대답에서 나는 부모/iframe 컨텐츠에 구운 ID를 사용하지 않고 부모 컨테이너를 참조하는 수단을 가져옵니다.
단순성 :
var iframe = $("#myframe");
$(iframe.get(0).contentWindow).on("resize", function(){
iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth);
iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight);
});
인라인 CSS 만 사용합니다.
<iframe src="http://example.com" style="resize: both;"
onload="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';"
onresize="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';">
</iframe>