我正在尝试使用 HTML/CSS/Javascript/jQuery 制作一个基本的画板。网格本身有一个设置大小,但当单击按钮时,系统会询问用户他们希望网格/画板有多大。当他们输入金额时,将创建一个新网格。我正在完成的项目说容器 div 的高度/宽度不应更改,但 .square div 应根据输入更改(例如,如果用户想要 5 x 5 网格,.square div 将根据输入更改大小输入)。我这样做了,但是我遇到了两个大问题:
1) 容器 div 中通常有剩余空间,因此其中一个 .square div 比其余的小得多,并且
2) 我不知道如何确保上下的 div 数量相同 - 6 x 6,而不是例如 4 x 9。
谢谢!
到目前为止,这是我的代码。如果内容困惑,请提前致歉 - 我才刚刚开始网络开发。
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery.js"></script>
<script type="text/javascript" src="sketchpad.js"></script>
<title>Sketchpad</title>
</head>
<body>
<button id="clearGrid">Clear Grid</button>
<div class="container">
</div> <!-- container -->
<body>
</html>
CSS
.container {
height: 960px;
width: 960px;
font-size: 0px;
margin: 150px auto;
}
#clearGrid {
display: block;
margin: 0 auto;
}
.square {
border: 1px solid black;
height: 20px;
width: 20px;
display: inline-block;
}
Javascript/jQuery
$(document).ready(function() {
var squareGrid = 256;
for (i = 0; i < squareGrid; i += 1) {
$(".container").append('<div class="square"></div>');
}
squareGrid;
$(".square").hover(function() {
$(this).css("background-color", "green");
}, function() {
$(this).css("background-color", "green");
});
$("#clearGrid").click(function() {
$(".square").css("background-color", "");
$(".square").remove(); //Removes current grid
var input = prompt("How big do you want to make your Sketchpad? Enter a number.");
if(isNaN(input))
alert("Please enter a number.");
else {
$(".square").removeAttr("width");
$(".square").removeAttr("height");
for (l = 0; l < (input * input); l += 1) {
$(".square").css("width", ".container" / input);
$(".square").css("height", ".container" / input);
$(".container").append('<div class="square"></div>');
}
};
$(".square").hover(function() {
$(this).css("background-color", "green");
}, function() {
$(this).css("background-color", "green");
});
});
});
最佳答案
jQuery
var w = $('.container').outerWidth();
var h = $('.container').outerHeight();
$('.square').outerWidth(w).outerHeight(h);
CSS
html {
box-sizing: border-box;
font: 500 16px/1.45 Consolas;
}
*, *:before, *:after {
box-sizing: border-box;
margin: 0;
padding: 0;
border: 0;
}
确保行和列中有多少个正方形的最简单方法是使用表格或使用 display: table
family of CSS properties .我更喜欢 flexbox
而不是 table
或 floats
。
另一个建议:Flexbox
关于javascript - 使用 Javascript/jQuery,如何更改 div 的高度/宽度,以便容器 div 中没有任何剩余空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31970924/