固定サイズのHTMLを、それよりも小さいサイズのIFRAMEに縮小して表示したかったので、その対処方法です。
課題
たとえば1440px X 1000pxの大きさのHTMLを幅800pxのIFRAMEに表示します。
解決方法
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="default.css">
</head>
<body>
<div id="wrapper">
<h1>Resize 1440px X 1000px iframe to width 800px</h1>
<iframe id="iframe" src="iframe-content.html"></iframe>
</div>
<a href="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: 0 auto 0 auto;
overflow: hidden;
width: 800px;
}
#iframe {
height: 1000px;
width: 1440px;
}
default.js
(function (window, document, $) {
let iframe = $('#iframe');
let wrapper = iframe.parent();
let width = wrapper.width();
let ratio = width / iframe.width();
console.log(`Ratio: ${ratio}`);
// IFRAME自体は読み込みページの大きさにCSSで適用している。
// それを#wrapperのサイズにスケールインする。
// https://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-an-iframe
iframe
.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を使用。