iframe의 폭과 높이를 콘텐츠에 맞게 조정
자동 조정을 위한 솔루션이 필요합니다.width
★★★★★★★★★★★★★★★★★」height
iframe
그 내용에 거의 맞지 않습니다. 수 있다는 입니다.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>
임베디드용 원라이너 솔루션: 최소 크기에서 시작하여 콘텐츠 크기로 확장합니다.스크립트 태그는 필요 없습니다.
<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 플러그인.
를 사용하는 크로스 보우서 크로스 도메인 라이브러리mutationObserver
postMessage
iFrame 。j의 합니다.질문합니다.
지금까지 제공된 모든 솔루션은 한 번 벗어난 크기만 고려합니다.컨텐츠가 수정된 후에 iFrame의 크기를 조정할 수 있도록 하고 싶다고 말씀하셨습니다.그러기 위해서는 iFrame 내에서 기능을 실행해야 합니다(콘텐츠가 변경되면 콘텐츠가 변경되었음을 알리는 이벤트를 실행해야 합니다).
iFrame 내의 코드가 iFrame 내의 DOM에만 한정되어 있는 것 같아서(iFrame을 편집할 수 없는 것), iFrame 외부에서 실행된 코드가 iFrame 외부의 DOM에 막혀서(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>
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;
}
지구상의 모든 것을 시도해 본 후에, 이것은 나에게 정말 효과가 있다.
index.displaces를 표시합니다.
<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>
이 코드를 사용하여 모든 iframe(클래스 autoHeight 포함)이 페이지에 로드될 때 높이를 자동으로 조정합니다.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();
});
이것은 확실한 증명 솔루션이다.
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>
맥락
웹 확장의 맥락에서 직접 해야 했습니다. 웹 은 각하고 이 는 UI의 내부에 합니다.iframe
에 .iframe
.iframe
그 자체입니다.
리액트를 사용하지만 이 개념은 모든 라이브러리에 적용됩니다.
마이솔루션(페이지와 iframe을 모두 제어하는 것을 전제로 합니다.
<고객명>iframe
body
이치이렇게 하면 내부의 요소들이 필요한 모든 공간을 사용하여 배치될 수 있습니다.★★★의 width
★★★★★★★★★★★★★★★★★」height
100%이 100%이기인 것 같다.width = 300px
★★★★★★★★★★★★★★★★★」height = 150px
)
/* something like this */
body {
width: 99999px;
height: 99999px;
}
그런 다음 iframe UI를 div 안에 모두 삽입하고 스타일을 부여했습니다.
#ui-root {
display: 'inline-block';
}
에 내 후#ui-root
(Respect에서 나는 이것을 안에서 한다.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)
위의 Garnaph의 훌륭한 솔루션을 약간 수정했습니다.그의 솔루션은 행사 직전 크기를 기준으로 iframe 크기를 수정한 것 같습니다.제 상황(iframe에 의한 메일 송신)에서는, iframe의 높이를 송신 직후에 변경할 필요가 있었습니다.예를 들어, 송신 후의 검증 에러나 「감사합니다」메시지를 표시합니다.
nested 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>
작동은 했지만 크로스 브라우저 기능에 대해서는 잘 모르겠습니다.
나는 몇 가지 실험 끝에 다른 해결책을 찾아냈다.저는 이 질문에 대해 '최적의 답변'으로 표시된 코드를 사용했지만 작동하지 않았습니다.제 추측으로는 당시 제 프로그램에서 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';
};
스크롤 바를 제거하려면 높이에 4개 이상의 픽셀을 추가해야 합니다(iframe의 이상한 버그/효과).폭은 더 낯설기 때문에 본체 폭에 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)에서 테스트를 조금 해봤습니다.아직 검사가 더 남았으니 어떻게 하는지 알려주세요.
IFRAME 콘텐츠와 부모 창을 모두 제어할 수 있는 경우 iFrame Resizer가 필요합니다.
이 라이브러리를 통해 동일한 도메인 및 교차 도메인 iFrames의 높이와 너비의 크기를 포함된 콘텐츠에 맞게 자동으로 조정할 수 있습니다.iFrames 사용 시 가장 일반적인 문제를 해결하기 위한 다양한 기능을 제공합니다.이러한 기능은 다음과 같습니다.
- 콘텐츠 크기에 맞게 iFrame 높이 및 폭 크기 조정.
- 여러 개의 중첩된 iFrames에서 작동합니다.
- 크로스 도메인 iFrames의 도메인 인증.
- 복잡한 CSS 레이아웃을 지원하기 위한 다양한 페이지사이즈 계산 방법을 제공합니다.
- MutationObserver를 사용하여 페이지 크기를 변경할 수 있는 DOM의 변경을 검출합니다.
- 페이지 크기를 변경할 수 있는 이벤트(윈도 크기 조정, CSS 애니메이션 및 전환, 방향 변경 및 마우스 이벤트)를 검출합니다.
- post Message를 통한 iFrame과 호스트 페이지 간의 심플한 메시징.
- iFrame 페이지 링크 수정 및 iFrame과 부모 페이지 간 링크 지원
- 사용자 정의 크기 조정 및 스크롤 방법을 제공합니다.
- 부모 위치 및 뷰포트 크기를 iFrame에 표시합니다.
- ViewerJ와 연계하여 PDF 및 ODF 문서를 지원합니다.
- IE8까지 폴백 지원.
위의 방법으로는 모두 동작할 수 없습니다.
javascript:
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>
환경: IE 10, Windows 7 x 64
고정 석면비로 생활할 수 있고 응답성이 뛰어난 iframe을 원하는 경우 이 코드가 유용합니다.그냥 CSS 규칙이야.
.iframe-container {
overflow: hidden;
/* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16=
0.5625) */
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
iframe에는 div를 컨테이너로 지정해야 합니다.
<div class="iframe-container">
<iframe src="http://example.org"></iframe>
</div>
소스코드는 이 사이트에 근거하고 있으며, 벤 마샬은 좋은 설명을 하고 있습니다.
존재하지 않는 것처럼 행동하는 "유령 같은" 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
이것은 최신 브라우저로 동작합니다!
다음은 몇 가지 방법입니다.
<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% 폭과 높이로 만듭니다.본문에는 스크롤 바가 없기 때문에 iframe이 페이지의 경계를 넘지 않을 수 있습니다.이렇게 하면 iFrame의 스크롤 바가 전폭으로 숨겨집니다!
소스: iframe 자동 높이 설정
누군가 여기 오는 경우:iframe에서 div를 삭제했을 때 솔루션에 문제가 있었습니다.iframe이 짧아지지 않았습니다.
작업을 수행하는 Jquery 플러그인이 있습니다.
http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html
이 리사이저가 더 잘 작동한다는 것을 알게 되었습니다.
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 src="" frameborder="0" id="iframe" width="100%"></iframe>
j쿼리
<script>
var valueSize = $( "#iframe" ).offset();
var totalsize = (valueSize.top * 2) + valueSize.left;
$( "#iframe" ).height(totalsize);
</script>
분명히 많은 시나리오가 있지만 문서와 iframe에 동일한 도메인을 사용하고 iframe 콘텐츠의 끝에 이 도메인을 추가할 수 있었습니다.
var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';
그러면 상위 컨테이너가 '찾기'된 다음 50픽셀의 퍼지 팩터에 더해지는 길이를 설정하여 스크롤 막대를 제거합니다.
문서 높이 변경을 '관찰'할 수 있는 것은 없습니다.이것은, 사용 예에 필요 없었습니다.제 답변에서는 부모/iframe 콘텐츠에 내장된 ID를 사용하지 않고 부모 컨테이너를 참조할 수 있는 수단을 가져옵니다.
function resizeIFrameToFitContent(frame) {
if (frame == null) {
return true;
}
var docEl = null;
var isFirefox = navigator.userAgent.search("Firefox") >= 0;
if (isFirefox && frame.contentDocument != null) {
docEl = frame.contentDocument.documentElement;
} else if (frame.contentWindow != null) {
docEl = frame.contentWindow.document.body;
}
if (docEl == null) {
return;
}
var maxWidth = docEl.scrollWidth;
var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));
frame.width = maxWidth;
frame.height = maxHeight;
frame.style.width = frame.width + "px";
frame.style.height = frame.height + "px";
if (maxHeight > 20) {
frame.height = maxHeight;
frame.style.height = frame.height + "px";
} else {
frame.style.height = "100%";
}
if (maxWidth > 0) {
frame.width = maxWidth;
frame.style.width = frame.width + "px";
} else {
frame.style.width = "100%";
}
}
ifram 스타일:
.myIFrameStyle {
float: left;
clear: both;
width: 100%;
height: 200px;
padding: 5px;
margin: 0px;
border: 1px solid gray;
overflow: hidden;
}
iframe 태그:
<iframe id="myIframe" src="" class="myIFrameStyle"> </iframe>
스크립트 태그:
<script type="text/javascript">
$(document).ready(function () {
$('myIFrame').load(function () {
resizeIFrameToFitContent(this);
});
});
</script>
이 방법은 다음과 같습니다(FF/Crome에서 테스트됨).
<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, text, ads 등에 대해 일반적으로 행해지는 스케일링에 대응할 수 있도록 삽입했습니다.스케일링이 실장되어 있지 않은 경우는 0을 입력해 주세요.
이게 내가 부하나 상황이 바뀌었을 때 하는 방법이야.
parent.jQuery("#frame").height(document.body.scrollHeight+50);
no jQuery cross-origin 솔루션을 찾고 있다면 제 아이디어를 참고해 주십시오.
<main id="container"></main>
<script>
fetch('https://example.com').then(response => {
return response.text();
}).then(data => {
const iframeContainer = window.document.getElementById('container');
const iframe = document.createElement('iframe');
iframe.frameBorder = 'none';
iframe.width = '100%';
iframe.addEventListener("load", function() {
iframe.height = iframe.contentWindow.document.body.scrollHeight;
})
const finalHtml = data;
const blob = new Blob([finalHtml], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
iframeContainer.appendChild(iframe);
})
</script>
나는 여기서 많은 답을 읽었지만 거의 모든 사람들이 일종의 교차 기원 프레임 블록을 주었다.
오류 예:
수집되지 않은 DOMException:오리진이 "null"인 프레임이 교차 오리진 프레임에 액세스하는 것을 차단했습니다.
관련 스레드의 답변에 대해서도 동일합니다.
스크롤바를 사용하지 않고 내용에 따라 iframe이 자동으로 높이를 조정하도록 합니까?
.iFrame Resizer
또는 유사한 라이브러리도 마찬가지입니다.
@bboydflo로부터의 답변은 가깝지만 완전한 예가 누락되어 있습니다.https://stackoverflow.com/a/52204841/3850405
사용하고 있다width="100%"
를 위해iframe
그러나 코드를 너비에 맞게 수정할 수도 있습니다.
이렇게 해서 커스텀 높이 설정을 해결했습니다.iframe
:
내장iframe
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site" />
<title>Test with embedded iframe</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
<script type="text/javascript">
window.addEventListener('message', receiveMessage, false);
function receiveMessage(evt) {
console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
// Do we trust the sender of this message?
if (evt.origin !== "https://localhost:44335") {
return;
}
if (evt.data.type === "frame-resized") {
document.getElementById("ifrm").style.height = evt.data.value + "px";
}
}
</script>
</body>
</html>
iframe source
, 예:Create React App
다만HTML
그리고.JS
사용됩니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site created using create-react-app" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript">
//Don't run unless in an iframe
if (self !== top) {
var rootHeight;
setInterval(function () {
var rootElement = document.getElementById("root");
if (rootElement) {
var currentRootHeight = rootElement.offsetHeight;
//Only send values if height has changed since last time
if (rootHeight !== currentRootHeight) {
//postMessage to set iframe height
window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
rootHeight = currentRootHeight;
}
}
}
, 1000);
}
</script>
</body>
</html>
다음 코드setInterval
물론 수정은 가능하지만 다이내믹한 콘텐츠와 잘 어울립니다. setInterval
콘텐츠가 에 포함되어 있는 경우에만 활성화 됩니다.iframe
그리고.postMessage
높이가 변경된 경우에만 메시지를 보냅니다.
에 대한 자세한 내용을 참조해 주세요.Window.postMessage()
여기에서는, 델이 달성하고 싶은 것에 매우 적합합니다.
window.postMessage() 메서드는 Window 오브젝트 간(예를 들어 생성된 페이지와 팝업 간 또는 페이지와 iframe에 포함된 페이지와 iframe 간)에 안전하게 크로스 오리진 통신을 가능하게 합니다.
통상, 다른 페이지의 스크립트는, 같은 프로토콜, 포토 번호, 및 호스트(「같은 발신기지 폴리시」라고도 불린다)를 공유하는 경우에 한해, 서로 액세스 할 수 있습니다.window.post Message()는 이 제한을 안전하게 회피하기 위한 제어 메커니즘을 제공합니다(적절하게 사용되는 경우).
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
폭과 높이를 100%로 하고 싶은 경우iframe
저는 이렇게 하고 싶어요.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description"
content="Web site" />
<style>
body {
margin: 0; /* Reset default margin */
}
iframe {
display: block; /* iframes are inline by default */
background: #000;
border: none; /* Reset default border */
height: 100vh; /* Viewport-relative units */
width: 100vw;
}
</style>
<title>Test with embedded iframe</title>
</head>
<body>
<iframe src="https://localhost:44335/package/details?key=123"></iframe>
</body>
</html>
출처:
https://stackoverflow.com/a/27853830/3850405
심플성:
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);
});
언급URL : https://stackoverflow.com/questions/819416/adjust-width-and-height-of-iframe-to-fit-with-content-in-it
'programing' 카테고리의 다른 글
Javascript/Node로 작성된 긴 SQL 문을 구성하는 방법 (0) | 2022.10.31 |
---|---|
jinja python 템플릿에서 쉼표로 구분된 목록을 출력하려면 어떻게 해야 합니까? (0) | 2022.10.31 |
JUnit 5에서는 모든 테스트 전에 코드를 실행하는 방법 (0) | 2022.10.31 |
Comparator를 사용하여 커스텀 정렬 순서를 정의하려면 어떻게 해야 합니까? (0) | 2022.10.31 |
SQL에서 Lef-most 조건을 충족하는 첫 번째 레코드를 가져오는 중 (0) | 2022.10.31 |