2017-09-21 85 views
0

我需要調整一些塊的大小以填充窗口大小調整時產生的空白(我認爲這可以通過javascript完成),但我怎麼能這樣做呢?在調整窗口大小時自動調整div容器上的圖像

var txt = ""; 
 
txt += "<p>innerWidth: " + window.innerWidth + " px</p>"; 
 
txt += "<p>outerWidth: " + window.outerWidth + " px</p>"; 
 

 
document.getElementById("demo").innerHTML = txt;
.container { 
 
    width:100%; 
 
    background:#fff; 
 
    height:300px; 
 
} 
 

 
.fixed-block { 
 
    float:left; 
 
    height:80px; 
 
    border:solid 2px #000; 
 
    min-width:70px; 
 
    background:#777; 
 
    width:23%; 
 
}
<div class="container"> 
 
    <div class="fixed-block"> 
 
    </div> 
 
    <div class="fixed-block"> 
 
    </div> 
 
    <div class="fixed-bblock"> 
 
    </div> 
 
    <div class="fixed-block"> 
 
    </div> 
 
    <div class="fixed-block"> 
 
    </div> 
 
</div> 
 
<div id="demo"></div>

這裏是jsfiddle

+0

你嘗試過什麼至今? – WhatsThePoint

+0

我曾嘗試轉換flexbox和javascript。它似乎是一個需要JavaScript代碼,可以控制容器的大小,並調整大小以查詢 – Roland

回答

0

類似的東西?

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
    </head> 
    <body> 

     <div class="container"> 
      <div class="fixed-block"></div> 
      <div class="fixed-block"></div> 
      <div class="fixed-block"></div> 
      <div class="fixed-block"></div> 
      <div class="fixed-block"></div> 
     </div> 

     <script> 
      window.onload = resizeDivs; 
      window.onresize = resizeDivs; 

      function resizeDivs() { 
       var container = document.querySelector('.container'); 

       // Compute new size: 
       var divs = document.querySelectorAll('.fixed-block'); 
       var divNb = divs.length; 
       var divWidth = Math.round(container.clientWidth/divNb) -0.5; 
       var divHeight = container.clientHeight; 

       // Apply size to the divs 
       for(var i=0; i<divNb; i++) { 
        var div = divs[i]; 
        div.style.width = divWidth + 'px'; 
        div.style.height = divHeight + 'px'; 
       } 
      } 
     </script> 

     <style> 
      body { 
       background: lightgrey; 
      } 

      .container { 
       width:100%; 
       background:#fff; 
       height:300px; 
      } 

      .fixed-block { 
       float:left; 
       height:80px; 
       box-sizing: border-box;/*important as border should not be added to the size*/ 
       border:solid 2px #000; 
       min-width:70px; 
       background:#777; 
       width:23%; 
      } 
     </style> 
    </body> 
</html> 

編輯:小改善與回合計算,並在窗口開通執行所調整

0

您可以使用CSS與Flexbox的做到這一點,讓你開始:

.container { 
    width:100%; 
    background:#fff; 
    height:300px; 
    display: flex; 
    flex-direction: row; 
    flex-wrap: wrap; 
} 

.fixed-block { 
    height:80px; 
    border:solid 2px #000; 
    background:#777; 
    flex: 1 0 70px; 
} 
相關問題