LoginSignup
144
144

More than 5 years have passed since last update.

JQueryで読み込み時とリサイズ時にブラウザサイズに横幅を合わせる

Last updated at Posted at 2014-04-26

レスポンシブデザインとかの横幅100%をJQueryで処理

こんな時に便利

  • video要素ではwidthおよびheight属性は、パーセントでの値指定が出来ない
  • レスポンシブデザインされていないページを処理する場合

読み込み時とリサイズ時を同時に処理する

読み込み時だけで処理するとブラウザサイズを変更した時に対応出来ないので、
JQueryではloadresizeを合わせて記載すればOK!

sample.js
$(window).on('load resize', function(){
// 処理を記載
});

読み込み時とリサイズ時を同時に処理する

例えば、下記のようなhtmlだと

index.html
<div id="wrapper">
 内容
</div>

$(window).width()でブラウザの横幅を取得し、要素のwidth属性に値をセットする。
height属性は、widthの値と動画の元サイズ比率から自動判断される為今回は特に設定なし。

sample.js
var w = $(window).width() * 1.05; //IEに対応させる為1.05倍
$('div#wrapper').attr('width', w);

完成系

これで完成。

sample.js
$(window).on('load resize', function(){
var w = $(window).width() * 1.05;
$('div#wrapper').attr('width', w);
});
144
144
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
144
144