Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8679

IFRAMEにコンテンツをフィットさせるには

$
0
0

固定サイズのHTMLを、それよりも小さいサイズのIFRAMEに縮小して表示したかったので、その対処方法です。

課題

たとえば1440px X 1000pxの大きさのHTMLを幅800pxのIFRAMEに表示します。

解決方法

index.html
<!DOCTYPE html><htmllang="ja"><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"crossorigin="anonymous"><linkrel="stylesheet"href="default.css"></head><body><divid="wrapper"><h1>Resize 1440px X 1000px iframe to width 800px</h1><iframeid="iframe"src="iframe-content.html"></iframe></div><ahref="iframe-content.html"target="_blank">iframe-content.html</a></body><script src="https://code.jquery.com/jquery-3.4.1.min.js"integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="crossorigin="anonymous"></script><script src="default.js"></script></html>
default.css
body{text-align:center;}#wrapper{margin:0auto0auto;overflow:hidden;width:800px;}#iframe{height:1000px;width:1440px;}
default.js
(function(window,document,$){letiframe=$('#iframe');letwrapper=iframe.parent();letwidth=wrapper.width();letratio=width/iframe.width();console.log(`Ratio: ${ratio}`);// IFRAME自体は読み込みページの大きさにCSSで適用している。// それを#wrapperのサイズにスケールインする。// https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-an-iframeiframe.css('-ms-transform',`scale(${ratio})`).css('-moz-transform',`scale(${ratio})`).css('-o-transform',`scale(${ratio})`).css('-webkit-transform',`scale(${ratio})`).css('transform',`scale(${ratio})`).css('-ms-transform-origin','0 0').css('-moz-transform-origin','0 0').css('-o-transform-origin','0 0').css('-webkit-transform-origin','0 0').css('transform-origin','0 0');// #iframeのひとつ上のラッパー#wrapperの高さを同じ倍率で変更する。// これをしないとうまくもともとのIFRAMEの高さのままになる。wrapper.height(wrapper.height()*ratio);})(window,window.document,window.jQuery);

ポイント

  • 同じ倍率で高さも変える必要もあるので、JavaScriptで対応します。
  • 参考サイトにある通り、CSSで縮小します。
  • IFRAMEのサイズは読み込んでいるコンテンツのサイズと同じにしておく。
  • IFRAMEをラッパーで囲みます。CSSで指定したサイズの領域が取られているのでラッパーのdivで高さを調整しています。
  • 面倒だったのでjQueryを使用。

demo

参考サイト

How can I scale the content of an iframe?


Viewing all articles
Browse latest Browse all 8679


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>