2017-04-06 15 views
0

divを作成して、画面の境界を超えない高さと高さを維持するアスペクト比を維持しようとしています。jquery:アスペクト比を維持してウィンドウ内にdivを含める

これは私が今持っているコードです:

<div class="container"></div> 

wW=$(window).width(); 
wH=$(window).height(); 
wHx=(wW/16)*9; 
wWx=(wH/9)*16; 
if(wW>wWx){ 
    vH1=$('.container').height(); 
    vW1=(vH1/9)*16; 
    vP1=($(window).width()-vW1)*0.5; 
    $('.container').css('width',vW1+'px'); 
    $('.container').css('left',vP1+'px'); 
    $('.container').css('height','100%'); 
    $('.container').css('top','0'); 
} 
if(wH>wHx){ 
    vW2=$('.container').width(); 
    vH2=(vW2/16)*9; 
    vP2=($(window).height()-vH2)*0.5; 
    $('.container').css('height',vH2+'px'); 
    $('.container').css('top',vP2+'px'); 
    $('.container').css('width','100%'); 
    $('.container').css('left','0'); 
} 

それはほとんど意図したとおりに動作しますが、それはいくつかのランダムな状況で失敗し、ページが問題を解決するためにリフレッシュする必要があります。

編集:同じ機能は、(それがサイズ変更中にいくつかのランダムな例では失敗した)リサイズ上で実行されます。

$(window).resize(function(){ 
    ......... 
}); 

EDIT2:スクリプトが失敗し、手動でウィンドウのサイズを変更して、最小化/最大化ボタンをクリックした後ブラウザのChromeとFirefoxで同じ結果が得られました。

答えて

1

これは助けることができる

// HTML 
<div class="container"></div> 

// CSS (SASS) 
.container { 
    background: red; 
    max-width: 100%; 

    &:before { 
    content: ''; 
    display: block; 
    // for 16/9 this is the height you need 
    padding-top: 56.25%; 

    } 
} 

// JavaScript 
$(function(){ 
    $(window).resize(function(){ 
    var width = $(window).width(), 
     height = $(window).height(); 

    if (width/height > 16/9) { 
     $('.container').css('max-width', height * 16/9); 
    } else { 
     $('.container').css('max-width', '100%'); 
    } 
    }) 
    // trigger resize so it takes the 
    // right size on load 
    .trigger('resize'); 

}); 

examle http://codepen.io/istavros/full/vxwVoW/

+0

はい、私は目に見えるwindow.This内側のdivを入れたいですCSSの手法では縦横比は保持されますが、可視ウィンドウに含まれるdivは保持されません。 – user1885099

+0

私の答えを更新しました。小さなJavaScriptを追加すると、ウィンドウの比率が16/9より大きい場合に比率を維持することができます – istavros

+0

この回答が役に立った場合、あなたの質問への回答として受け入れることができますか? – istavros

0

私は、これはあなたが探しているものであると信じて:

<div class="container"></div> 
//CSS 
.container { 
max-width: 100vw; 
max-height: 100vh; 
} 
関連する問題