복붙노트

[JQUERY] 메이크업은 iframe 높이를 동적 JQUERY / 자바 스크립트있어 문을 내용에 따라

JQUERY

메이크업은 iframe 높이를 동적 JQUERY / 자바 스크립트있어 문을 내용에 따라

해결법


  1. 1.당신은 사용하여 IFRAME의 내용의 높이를 검색 할 수 있습니다 : contentWindow.document.body.scrollHeight

    당신은 사용하여 IFRAME의 내용의 높이를 검색 할 수 있습니다 : contentWindow.document.body.scrollHeight

    IFRAME을가로드 된 후에는 다음을 수행하여 높이를 변경할 수 있습니다 :

    <script type="text/javascript">
      function iframeLoaded() {
          var iFrameID = document.getElementById('idIframe');
          if(iFrameID) {
                // here you can make the height, I delete it first, then I make it again
                iFrameID.height = "";
                iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
          }   
      }
    </script>   
    

    그런 다음, IFRAME 태그에,이 같은 핸들러를 연결 :

    <iframe id="idIframe" onload="iframeLoaded()" ...
    

    내가 추가로 필요한 경우 전 양식을 제출 내에 발생 후 IFRAME 자체에서 iframeLoaded를 호출하는 동안 나는 상황 a를했다. 당신하여 IFRAME의 내용 스크립트에서 다음을 수행하여 그 수행 할 수 있습니다 :

    parent.iframeLoaded();
    

  2. 2.아리스 토스에 약간 개선 답 ...

    아리스 토스에 약간 개선 답 ...

    <script type="text/javascript">
      function resizeIframe(iframe) {
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
      }
    </script>  
    

    그런 다음 다음과 같이 당신의 iframe에 선언

    <iframe onload="resizeIframe(this)" ...
    

    두 개의 작은 개선이 있습니다 :

    편집하다: 프레임의 내용은 항상 다음 변경되면 호출

    parent.resizeIframe(this.frameElement); 
    

    업데이트 후 iframe을 내에서. 같은 기원을 위해 작동합니다.

    또는 자동으로 감지 :

      // on resize
      this.container = this.frameElement.contentWindow.document.body;
    
      this.watch = () => {
        cancelAnimationFrame(this.watcher);
    
        if (this.lastScrollHeight !== container.scrollHeight) {
          parent.resizeIframeToContentSize(this.frameElement);  
        }
        this.lastScrollHeight = container.scrollHeight;
        this.watcher = requestAnimationFrame(this.watch);
      };
      this.watcher = window.requestAnimationFrame(this.watch);
    

  3. 3.허용-에서 사파리 나 크롬에서 지원되지 않습니다 : 나는 X-FRAME-OPTIONS 이후 허용 대답이 충분하지 않은 것으로 나타났다. Disqus에에서 벤 식초에 의해 주어진 프리젠 테이션에서 발견 대신 다른 방법으로 갔다. 아이디어는 부모 창에 이벤트 리스너를 추가하는 것입니다, 다음은 iframe 내부 (iframe을 크기를 조정) 뭔가를 할 그것을 말하는 부모에게 이벤트를 보낼 window.postMessage를 사용합니다.

    허용-에서 사파리 나 크롬에서 지원되지 않습니다 : 나는 X-FRAME-OPTIONS 이후 허용 대답이 충분하지 않은 것으로 나타났다. Disqus에에서 벤 식초에 의해 주어진 프리젠 테이션에서 발견 대신 다른 방법으로 갔다. 아이디어는 부모 창에 이벤트 리스너를 추가하는 것입니다, 다음은 iframe 내부 (iframe을 크기를 조정) 뭔가를 할 그것을 말하는 부모에게 이벤트를 보낼 window.postMessage를 사용합니다.

    부모 문서에 그래서, 이벤트 리스너를 추가 :

    window.addEventListener('message', function(e) {
      var $iframe = jQuery("#myIframe");
      var eventName = e.data[0];
      var data = e.data[1];
      switch(eventName) {
        case 'setHeight':
          $iframe.height(data);
          break;
      }
    }, false);
    

    그리고 iframe을 내부에 메시지를 게시하는 함수를 작성 :

    function resize() {
      var height = document.getElementsByTagName("html")[0].scrollHeight;
      window.parent.postMessage(["setHeight", height], "*"); 
    }
    

    마지막으로, iframe이 내부 크기 조정 기능을 발사 body 태그에에 onLoad를 추가 :

    <body onLoad="resize();">
    

  4. 4.이것은 나를 위해 일한 iframe을,이 추가 :

    이것은 나를 위해 일한 iframe을,이 추가 :

    onload="this.height=this.contentWindow.document.body.scrollHeight;"
    

    당신이 jQuery를 사용하는 경우 그리고이 코드를 시도 :

    onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"
    

  5. 5.iframe에 내용의 높이를 얻기 위해 당신이 볼 수있는 네 가지 속성이 있습니다.

    iframe에 내용의 높이를 얻기 위해 당신이 볼 수있는 네 가지 속성이 있습니다.

    document.documentElement.scrollHeight
    document.documentElement.offsetHeight
    document.body.scrollHeight
    document.body.offsetHeight
    

    슬프게도 그들은 모두 다른 대답을 줄 수있는 이러한 브라우저 사이에 일관성이 있습니다. 0으로 몸 마진을 설정하면 다음 document.body.offsetHeight는 가장 좋은 대답을 제공합니다. 올바른 값이 기능을 시도 얻으려면; 이는 또한 내용 변경하거나 브라우저의 크기를 조정할 때 iframe이에게 올바른 크기를 유지 한 후 보이는 것을 iframe을-리사이 라이브러리에서 가져옵니다.

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            function getPixelValue(value) {
                var PIXEL = /^\d+(px)?$/i;
    
                if (PIXEL.test(value)) {
                    return parseInt(value,base);
                }
    
                var 
                    style = el.style.left,
                    runtimeStyle = el.runtimeStyle.left;
    
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft;
                el.style.left = style;
                el.runtimeStyle.left = runtimeStyle;
    
                return value;
            }
    
            var 
                el = document.body,
                retVal = 0;
    
            if (document.defaultView && document.defaultView.getComputedStyle) {
                retVal =  document.defaultView.getComputedStyle(el, null)[prop];
            } else {//IE8 & below
                retVal =  getPixelValue(el.currentStyle[prop]);
            } 
    
            return parseInt(retVal,10);
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    

  6. 6.내가 일부 변경했다, 그래서 다른 대답은 나를 위해 작동하지 않았다. 이 의지의 도움을 희망

    내가 일부 변경했다, 그래서 다른 대답은 나를 위해 작동하지 않았다. 이 의지의 도움을 희망

    $('#iframe').on("load", function() {
        var iframe = $(window.top.document).find("#iframe");
        iframe.height(iframe[0].ownerDocument.body.scrollHeight+'px' );
    });
    

  7. 7.이런 경우에이 사람을 도움이됩니다. 100 % : 나는 일이를 얻을려고 밖으로 내 머리를 당겨 한 후 나는 iframe이 높이와 클래스 항목을 가지고 것으로 나타났습니다. 나는이를 제거 할 때, 모든 것이로 예상했다. 그래서, 어떤 CSS 충돌을 확인하십시오.

    이런 경우에이 사람을 도움이됩니다. 100 % : 나는 일이를 얻을려고 밖으로 내 머리를 당겨 한 후 나는 iframe이 높이와 클래스 항목을 가지고 것으로 나타났습니다. 나는이를 제거 할 때, 모든 것이로 예상했다. 그래서, 어떤 CSS 충돌을 확인하십시오.


  8. 8.당신은 또한 항상 레이아웃 브라우저 페인트 전에 호출 될 것이다 (예를 들어, 전갱이의 대답 @에서) 당신의 resizeIframe에 반복 requestAnimationFrame을 추가 할 수 있으며, 그 내용이 자신의 높이를 변경 한 때 당신은 iframe 대응의 높이를 업데이트 할 수 있습니다. 예를 들면 등의 입력 양식, 지연 로딩 콘텐츠

    당신은 또한 항상 레이아웃 브라우저 페인트 전에 호출 될 것이다 (예를 들어, 전갱이의 대답 @에서) 당신의 resizeIframe에 반복 requestAnimationFrame을 추가 할 수 있으며, 그 내용이 자신의 높이를 변경 한 때 당신은 iframe 대응의 높이를 업데이트 할 수 있습니다. 예를 들면 등의 입력 양식, 지연 로딩 콘텐츠

    <script type="text/javascript">
      function resizeIframe(iframe) {
        iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        window.requestAnimationFrame(() => resizeIframe(iframe));
      }
    </script>  
    
    <iframe onload="resizeIframe(this)" ...
    

    콜백은 전체 성능에 큰 영향이없는 것으로 충분히 빨리해야한다


  9. 9.당신은 여기에 관련된 질문을 참조 할 수 있습니다 - 어떻게 너비와 부모 DIV 동일은 iframe의 높이를 만드는 방법?

    당신은 여기에 관련된 질문을 참조 할 수 있습니다 - 어떻게 너비와 부모 DIV 동일은 iframe의 높이를 만드는 방법?

    동적 높이를 설정합니다 -

    그리고 코드 - https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8


  10. 10.오히려 자바 스크립트 / JQuery와 가장 쉬운 방법을 사용하는 것보다 I의 FOUND입니다 :

    오히려 자바 스크립트 / JQuery와 가장 쉬운 방법을 사용하는 것보다 I의 FOUND입니다 :

    해당

    다음 브라우저 창 높이 1vh = 1 %. 높이의 이론 값이되고 그래서 세트 100vh하지만, 실질적으로 마법을했다 98vh.


  11. 11.절대 및 iframe 자동 내용에 따라 그 높이를 변경한다 : 단지 iframe이 컨테이너의 위치를 ​​확인

    절대 및 iframe 자동 내용에 따라 그 높이를 변경한다 : 단지 iframe이 컨테이너의 위치를 ​​확인

    <style>
       .iframe-container {
           display: block;
           position: absolute;
           /*change position as you need*/
           bottom: 0;
           left: 0;
           right: 0;
           top: 0;
       }
       iframe {
           margin: 0;
           padding: 0;
           border: 0;
           width: 100%;
           background-color: #fff;
       }
     </style>
     <div class="iframe-container">
         <iframe src="http://iframesourcepage"></iframe>
     </div>
    

  12. 12.나는, 나를 위해 일하는 아래 jQuery를하고 코드를 사용하고

    나는, 나를 위해 일하는 아래 jQuery를하고 코드를 사용하고

    var iframe = $(window.top.document).find("#iframe_id_here");
    iframe.height(iframe.contents().height()+'px' );
    

  13. 13.나는 트로이의 대답은 작동하지 않았다 발견했다. 이것은 아약스에 대한 재 작업 같은 코드입니다 :

    나는 트로이의 대답은 작동하지 않았다 발견했다. 이것은 아약스에 대한 재 작업 같은 코드입니다 :

    $.ajax({                                      
        url: 'data.php',    
        dataType: 'json',                             
    
        success: function(data)
        {
            // Put the data onto the page
    
            // Resize the iframe
            var iframe = $(window.top.document).find("#iframe");
            iframe.height( iframe[0].contentDocument.body.scrollHeight+'px' );
        }
    });
    

  14. 14.당신은 내가 사용 스크롤하지 않아도, 특히 하단에 차단 보인다 윈도우의 덩어리에 추가하려면 :

    당신은 내가 사용 스크롤하지 않아도, 특히 하단에 차단 보인다 윈도우의 덩어리에 추가하려면 :

    function resizeIframe(iframe) {
        var addHeight = 20; //or whatever size is being cut off
        iframe.height = iframe.contentWindow.document.body.scrollHeight + addHeight + "px";
      }
    

  15. 15.당신이 더 jQuery로하는 솔루션을 필요로 할 때 이것은 유용합니다. 이 경우 당신은 컨테이너를 추가 시도해야 및 백분율에에 패딩을 설정

    당신이 더 jQuery로하는 솔루션을 필요로 할 때 이것은 유용합니다. 이 경우 당신은 컨테이너를 추가 시도해야 및 백분율에에 패딩을 설정

    HTML 예제 코드 :

    <div class="iframecontainer">
        <iframe scrolling="no" src="..." class="iframeclass"width="999px" height="618px"></iframe>
    </div>
    

    CSS 예제 코드 :

    .iframeclass{
        position: absolute;
        top: 0;
        width: 100%;
    }
    
    .iframecontainer{
        position: relative;
        width: 100%;
        height: auto;
        padding-top: 61%;
    }
    

  16. 16.간단한 해결책은 콘텐츠 영역의 폭과 높이를 측정하고 아래 패딩 백분율을 계산하기 위해 이들 측정들을 사용하는 것이다.

    간단한 해결책은 콘텐츠 영역의 폭과 높이를 측정하고 아래 패딩 백분율을 계산하기 위해 이들 측정들을 사용하는 것이다.

    이 경우, 측정은 1680 X 720 픽셀이므로, 하단의 여백이 43 %로 나온다 1,680분의 720 = 0.43 × 100이다.

    .canvas-container {    
        position: relative;
        padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
        height: 0;
        overflow: hidden;   
    }
    
    .canvas-container iframe {    
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;   
    }
    

  17. 17.전갱이에 약간 개선 답 ...

    전갱이에 약간 개선 답 ...

    function resizeIframe(iframe) {
        var padding = 50;
        if (iframe.contentWindow.document.body.scrollHeight < (window.innerHeight - padding))
            iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        else
            iframe.height = (window.innerHeight - padding) + "px";
    }
    

    이것은 고려 반응 디자인과 거대한 높이가 iframe을위한 좋은 윈도우 화면 (브라우저, 전화)의 높이를합니다. 패딩은 위 경우 iframe을 아래에 원하는 패딩이 저점 전체 화면 이동을 나타냅니다.


  18. 18.

    jQuery('.home_vidio_img1 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery(this).replaceWith(video);
    });
    
    jQuery('.home_vidio_img2 img').click(function(){
        video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img3 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img4 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    

  19. 19.높이가 존재> 0 인 경우에 반드시 htmlspecialchars PHP () + 체크를 사용하여 샘플 :

    높이가 존재> 0 인 경우에 반드시 htmlspecialchars PHP () + 체크를 사용하여 샘플 :

    $my_html_markup = ''; // Insert here HTML markup with CSS, JS... '<html><head></head><body>...</body></html>'
    $iframe = '<iframe onload="if(this.contentWindow.document.body.scrollHeight) {this.height = this.contentWindow.document.body.scrollHeight;}" width="100%" src="javascript: \''. htmlspecialchars($my_html_markup) . '\'"></iframe>';
    

  20. 20.

    $(document).height() // - $('body').offset().top
    

    및 / 또는

    $(window).height()
    

    스택 오버플로 질문은 본문 요소의 높이를 얻는 방법을 참조하십시오.

    jQuery를에 몸의 높이를 찾으려면이 시도 :

    if $("body").height()
    

    그것은 방화범 경우 값이 없습니다. 아마도 그게 문제입니다.


  21. 21.당신은 CSS와 함께 할 수 있습니다 :

    당신은 CSS와 함께 할 수 있습니다 :

    <iframe
        frameborder="0"
        allow="autoplay; fullscreen"
        allowfullscreen
        width="100%"
        height="478"
        src="https://www.youtube.com/embed/tgbNymZ7vqY"
    >
    
  22. from https://stackoverflow.com/questions/9162933/make-iframe-height-dynamic-based-on-content-inside-jquery-javascript by cc-by-sa and MIT license