我试图用 colors 类设置 div 的宽度,无论是百分比还是像素,但我没能做到。
var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"];
for (var h = 0; h <= 4; h++) {
for (var i = 0; i <= colors.length - 1; i++) {
var element = "<div class='colors' id='color" + i + "'>" + colors[i] + "</div>";
var sample = "sahdkj";
$('#gameContainer').append(element);
};
$('#gameContainer').append("<br/><br/>");
}
body {
margin: 10px;
}
.container {
border: 2px solid #e7e7e7;
border-radius: 3px;
width: 407px;
}
.colors {
display: inline;
border: 1px solid black;
width: 20%;
position: relative;
top: 10px;
bottom: 10px;
margin: 10px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container" id="gameContainer">
</div>
</body>
最佳答案
将 display: inline;
更改为 display: inline-block;
var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"];
for (var h = 0; h <= 4; h++) {
for (var i = 0; i <= colors.length - 1; i++) {
var element = "<div class='colors' id='color" + i + "'>" + colors[i] + "</div>";
var sample = "sahdkj";
$('#gameContainer').append(element);
};
$('#gameContainer').append("<br/><br/>");
}
body {
margin: 10px;
}
.container {
border: 2px solid #e7e7e7;
border-radius: 3px;
width: 500px;
}
.colors {
display: inline-block;
border: 1px solid black;
width: 20%;
position: relative;
top: 10px;
bottom: 10px;
margin: 10px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="gameContainer">
</div>
关于javascript - 无法设置div的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48437157/