我正在創建 etch-a-sketch。目前,我想出了如何創建網格寬度用戶輸入值。但是當值改變時,網格大小會改變。我想讓網格的寬度在單元格值發生變化時保持不變。我該怎么做。我嘗試調整網格模板行和列。它沒有用
謝謝
這是我的代碼
.grid{
padding: 10px;
display: inline-grid;
justify-content: center;
border: 1px solid black;
gap: 1px;
}
.button-div{
padding: 10px;
display: flex;
justify-content: center;
}
const container = document.getElementById('container');
//div for buttons
const buttonDiv = document.createElement('div');
buttonDiv.classList.add('button-div');
container.appendChild(buttonDiv);
//A button to reset Everything
const resetButton = document.createElement('button');
resetButton.textContent = 'Reset';
buttonDiv.appendChild(resetButton);
//grid in a seperate div
const grid = document.createElement('div');
grid.classList.add('grid');
container.appendChild(grid);
//function to create grid
function makeGrid(value){
let gridWidth = 200 / value;
grid.style.gridTemplateColumns = `repeat(${value}, ${gridWidth}px)`;
grid.style.gridTemplateRows = `repeat(${value}, ${gridWidth}px)`;
for(let i = 0; i < value; i ){
for(let j = 0; j < value; j ){
const cell = document.createElement('div');
cell.classList.add('cell');
cell.addEventListener('mouseover', toBlack);
grid.appendChild(cell);
}
}
}
//to change the cell color to black on mouseover
function toBlack(e){
e.target.style.backgroundColor = 'black';
}
function resetGrid(){
const value = prompt('Input a number of Squares');
grid.innerHTML = '';
makeGrid(value);
}
resetButton.addEventListener('click',resetGrid);
window.onload = () => {makeGrid(16)};
uj5u.com熱心網友回復:
我在您的問題中復制 粘貼代碼以創建 jsfiddle:https ://jsfiddle.net/k8ebmqd4/
到目前為止,您創建的是一個固定大小.grid,其中內部的數量和大小div.cell取決于用戶輸入。正確理解你的問題,這不是你想要的。div.cell應該始終保持 12.5x12.5 (這就是我在小提琴上看到的)。如果是這種情況,只需將此行更改
let gridWidth = 200 / value;
為:
let gridWidth = 12.5;
現在.grid大小取決于其中的單元格數量。
根據以下評論解決方案:從 : 中洗掉樣式gap并.grid添加邊框。請參閱:https ://jsfiddle.net/t5akxof2/.cell.cell{border:1px solid #FFFFFF;}
uj5u.com熱心網友回復:
你云使用這個:
// Container for columns
.h-container {
display: flex;
flex-flow: column;
height: 100%;
}
// Container for rows
.w-container {
display: flex;
flex-flow: row;
height: 100%;
}
.container-needed {
flex: 0 1 auto;
}
.container-rest {
flex: 1 1 auto;
overflow: hidden;
}
HTML
<div class="w-container">
<div class="container-needed"> </div>
<div class=container-rest> </div>
</div>
有了這個,第一個元素需要盡可能多的元素,其余的第二個元素,如果你愿意,你可以添加兩個以上......容器可以是固定大小
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527445.html
標籤:javascripthtmljQuerydomCSS网格
