2017-09-21 72 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; 
} 
相关问题