2016-08-02 4 views
0

iframeのコンテンツの変更方法に基づいてiframeの高さを変更したいのですが、iframeのコンテンツの高さが150px未満の場合に問題が発生します。iframeの高さが150px未満の場合

FirefoxとChromeでこのコードをテストしたところ、同じ結果が得られました。 ここでテストできますhttps://jsfiddle.net/bqvc0pp5/17/

高さが指定されていないと私が見たことから、iframeは自動的に(ボーダーなしで)150pxになります。 この例では、値を300pxに増やしてから200pxに下げて50pxに下げました。 50pxが150pxに変換されるまで、すべてがうまく動作します。

var iframe = document.createElement('iframe'); 
    iframe.setAttribute("scrolling","no"); 

    iframe.onload =() => { 
     builtElement(); 
    }; 

    //append iframe to main document 
    document.body.appendChild(iframe); 

    var k=0; 


    function builtElement(){ 
     var div = document.createElement('div'); 
     div.style.height="50px"; 
     div.style.backgroundColor="salmon"; 
     iframe.contentWindow.document.body.style.margin="0px"; 
     iframe.contentWindow.document.body.appendChild(div); 

     div.addEventListener("click",() =>{ 
      if(k==0){ 
      div.style.height="300px"; 
      } 
      if(k==1){ 
      div.style.height="200px"; 
      } 
      if(k==2){ 
      div.style.height="50px"; 
      } 
      if(k>=2) k=0; 
      else k++; 
      updateIframeHeight(); 
     }); 
    } 


    function updateIframeHeight(){ 
     //I need to reset height or else scrollHeight will be the last max value 
     iframe.style.height=""; 
     var height = iframe.contentWindow.document.body.scrollHeight; 
     //this is a dirty hack where I can check if offsetHeight is lower than 150px 
     var offsetHeight = iframe.contentWindow.document.body.offsetHeight; 
     //if(offsetHeight<150) height=offsetHeight; 
     console.log("scrollHeight: "+height); 
     console.log("scrollHeight: "+offsetHeight); 
     iframe.style.height=height+"px"; 
    } 

私は少しハックを行うと、offsetHeightは、それが動作150ピクセルよりも低い場合に確認してください。

var offsetHeight = iframe.contentWindow.document.body.offsetHeight; 
    if(offsetHeight<150) height=offsetHeight; 

これはこれを行う最もよい方法ですか?

UPDATE:実際の例では、インラインフレーム本体は、複数の要素が含まれていますが、唯一の特定の要素が高さを変更する、そのための体を変更すると、scrollHeight

答えて

2

解決策が見つかりました。サイズを0pxに設定するだけです。私は以前iframe.style.height="";は、デフォルトで150ピクセルに高さを設定したのは何

iframe.style.height="0px"; 

。サイズが指定されていない場合、iframeのサイズは150pxになります。

0

、これは最終的な解決策ではなく、これはあなたを助けるかもしれませんハックなしで問題を解決してください:

[Fiddle][1]https://jsfiddle.net/Marouen/qskpdn8b/ 
+0

ありがとうございますが、これは私が探しているものではありません。私の実際の例では、ボディには複数のdivが含まれています.1つのdivだけがheightを変更すると、body scrollHeightを計算できるようにしたいと考えています。 –

+0

これはあなたが最初に投稿したquestipnではありませんでした!あなたはすぐに解決策を見つけることを願って –

+1

ありがとう。私は混乱を避けるためにメインのポストを更新しました –

関連する問題