Div容器用动态网格扩展

时间:2017-05-21 06:02:04

标签: javascript jquery html css grid

这是一个两个部分。我有一个由div(.unit)组成的动态网格,我试图在一个较大的div(#pallet)中包含它。网格根据用户在提示中给出的整数而增加。我的问题是如何在不使用绝对定位的情况下让较大的div相对于网格的大小进行扩展?网格也不会减少到用户给定的值,它只会增加。任何帮助将不胜感激!

$(document).ready(function() {   
  var userChoice = 10;

  for(var x = 0; x < userChoice; x++) {  
    for(var y = 0; y < userChoice; y++) { 
       var unit = $("<div class='unit'></div>"); 
       unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo
    }
  }

   $(".unit").hover(function(){   //jquery selects the "unit" div and issues a function on it to change the css 
   $(this).css("background-color", "black");   //this is in reference to .unit changing the css to black

  });


  document.getElementById("reset").onclick = gridReset;    //reset is the id of our button, so when it's clicked it will call our function gridReset


   function gridReset() {    //function grid reset first asks a prompt then stores the user's choice value in a variable and puts it through checks to see if its valid


   userChoice = prompt("Between 1 and 64 how big would you like your grid?");  //we put our user choice in the function so as to not call a prompt at the start of the page load AND to store the variable in the scope


   if (isNaN(userChoice)) {

    alert(userChoice + " is not a number");

   }
   else if (userChoice >= 65 || userChoice <= 0) {

    alert("Choose a number between 1 and 64");

   }

   else { 

     $(".unit").empty();        
     $(".unit").css("background-color", "blue");

     for(var x = 0; x < userChoice; x++) {  //for loop creates iteration of userChoice
     for(var y = 0; y < userChoice; y++) { //for loop creates iteration of userChoice

     var unit = $("<div class='unit'></div>"); //creates a variable "unit" = to a jquery div element with a class of unit 

     unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo

      $(".unit").hover(function(){   //jquery selects the "unit" div and issues a function on it to change the css 

      $(this).css("background-color", "black");   //this is in reference to 
.unit changing the css to black

    });


   }

  }
 }
}

  });

HTML:

<!DOCTYPE html>
<html>
<head>   
  <title>Odin Div Project</title> 
  <link rel="stylesheet" type="text/css" href="styles/styles.css" />
</head> 

<body>
  <button id="reset" type="button">Reset Grid</button>
  <div id="pallet">
  </div>
  <script type="text/javascript" src="scripts/jquery-3.2.0.min.js"> 
  </script>
  <script type="text/javascript" src="scripts/script.js"> </script>
</body>
</html>

CSS:

#pallet {
  position: relative;
  left: 425px;
  top: 150px;
  background-color: black;
  height: 440px;
  width: 440px;

}
.unit {
  position: relative;
  background-color: blue;
  height: 20px;
  width: 20px;
  margin: 1px;
  display: inline-block;
  float: left;
 }

0 个答案:

没有答案