投稿にembedしたiframe等の自動resize

Pocket

友人のWordPressで作ったサイトにて、スマホ向けのテーマを作って、mobile detectorを使って振り分けていrう
iframeでembedしたyoutubeなどの動画を、画面幅一杯に見せる方法を調べてみた。
特に有効なプラグインも見つからなかったので考えてみたところ、embedする動画等の条件は

  • iframeかobject
  • classなども決まっていることが多い
  • 幅は、その親elementにあわせれば良い
  • aspect比は変えない

ということで、それを処理してくれるよう、jqueryを使って書くと

$(document).ready(function() {
    $('iframe').each(function() {
        var parentWidth = $(this).parent().width();
        var width = $(this).width();
        var width = $(this).width();
        var height = $(this).height();
        var ratio = height/width;
        $(this).css("width", parentWidth); // Set new width
        $(this).css("height", parentWidth * ratio);  // Scale height based on ratio
    });
});

きっともう少し作り込むと、onorientationchange でも実行するようにできる。
正しくjqueryを使う方法については
http://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/
を参考にすると良い。
まっさらのWPから始めるなら、こちらのやり方を徹底するのも良いと思う。
参考にしたページ: