2015-08-16 36 views
1

我試圖完成兩兩件事:如果聲明適用於調整大小,還沒有準備好?

  1. 主要內容DIV將動態調整以適合窗口的確切高度。我實現這一目標具有這種功能:

    $(document).on('ready', function() { 
        panelsResize(); 
        $(window).on('resize', panelsResize); 
    }); 
    
    function panelsResize() { 
        var screenHeight = $(window).height(); 
        var screenWidth = $(window).width();   
        if (screenWidth > 768) { 
         $(".panels").css("height", screenHeight); 
        } 
    }; 
    

.panels適用於主體區域。

這有效。

  1. 我想填充.panels.large中的圖像。這些圖像需要保持高寬比,同時可以擴展。我已經根據我的代碼on this answer

這個工作,但沒有準備好。我不得不調整屏幕大小,降到媒體查詢的下方,將.large的顯示切換爲無。當我調整到更高的媒體查詢時,將顯示切換爲阻止,功能完美無缺。

任何想法?

這裏的函數(標記):

$(document).on('ready', function() { 
     bgResize(); 
     $(window).on('resize', bgResize); 
    }); 

    function bgResize(){ 
     $('.large').each(function() { 

     var th = $(window).height(),//box height 
      tw = $(window).width(),//box width 
      im = $(this).children('img'),//image 
      ih = im.height(),//inital image height 
      iw = im.width();//initial image width 

     if (iw < tw) { 
      im.css({ "width" : "100%", "height" : "auto" }); 
     } 
     else if (ih < th) { 
      im.css({ "height" : "100%", "width" : "auto" }); 
     } 

     var nh = im.height(),//new image height 
      nw = im.width(),//new image width 
      hd = (nh-th)/2,//half dif img/box height 
      wd = (nw-tw)/2;//half dif img/box width 

     if (nh<nw) { 
      im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left 
     } else { 
      im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top 
     } 

    }); 
}; 

這是HTML:

<ul id="homePanels"> 
     <li id="cat1" class="panels"> 
      <div class="large"> 
       <img src="#" alt="" /> 
      </div> 
      <div class="small"> 
       <img src="#" alt="" /> 
      </div> 
     </li> 
    </ul> 

的CSS:

#homePanels { 
    list-style: none; 
    margin:0; 
    padding:0; 
    overflow: hidden; 
} 

.large { 
    width:100%; 
    height:100%; 
} 

@media (min-width: 768px) { 
    .large{display: block;} 
    .small{display:none} 
} 

@media (max-width: 768px) { 
    .small {display:block;} 
    .large {display:none;} 
} 

回答

0

我認爲,如果你使用jQuery就緒()函數它會工作。

$(document).ready(function() { 
    bgResize(); 
    $(window).on('resize', bgResize); 
}); 
0

你只需要改變

$(document).on('ready', function() 

$(document).ready(function() 
0

謝謝!我對已準備好的事件做了改變。

我意識到使用圖像的寬度和高度引發了問題,因爲我抓住了基本上兩個0。所以,因爲我知道圖像的高寬比,所以我使用它在屏幕上調整圖像大小。

var screenHeight = $(window).height(), 
     screenWidth = $(window).width(), 
     aspectRatio = 0.57066014669927, 
     screenAspectRatio = screenHeight/screenWidth; 

    if (screenAspectRatio < aspectRatio){ 
     $("img").css({"width" : "100%" , "height" : "auto"}); 
    } else if (screenAspectRatio > aspectRatio){ 
     $("img").css({"width" : "auto" , "height" : "100%"}); 
    } 

但現在解決了。謝謝你的幫助!