我想不出 JS 中执行此操作的正确方法......在 6 div 的网格中,我想根据所做的选择显示/隐藏并调整大小。所以 2 个选择等于 50:50,3 个选择等于 33:33:33 等等。
注意,最大宽度为 3,深度为 2 行。
感谢您的帮助!
我对正确的技巧了解不够。
您可以通过使用 JavaScript 根据所做选择的数量动态调整网格布局来实现此目的。以下是帮助您实现这一目标的分步方法:
HTML 结构:使用 6 个 div 元素定义网格结构。 CSS:定义网格和 div 元素的基本样式。 JavaScript:添加逻辑来处理选择、显示/隐藏 div 元素,并相应地调整其大小。
这是一个示例实现:
document.addEventListener('DOMContentLoaded', () => {
const gridContainer = document.getElementById('grid-container');
const gridItems = document.querySelectorAll('.grid-item');
// Function to update the grid layout based on the number of selections
function updateGridLayout(selectionCount) {
// Determine the number of columns
const columns = Math.min(selectionCount, 3);
// Set the grid template columns based on the number of selections
gridContainer.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;
// Show/Hide and adjust the grid items
gridItems.forEach((item, index) => {
if (index < selectionCount) {
item.style.display = 'flex'; // Show the item
} else {
item.style.display = 'none'; // Hide the item
}
});
}
// Example: Call the function with different selection counts to test
updateGridLayout(2); // Show 2 items, each 50% width
// updateGridLayout(3); // Show 3 items, each 33.33% width
// updateGridLayout(4); // Show 4 items in a 2x2 grid
// updateGridLayout(5); // Show 5 items in a 3x2 grid
// updateGridLayout(6); // Show all 6 items in a 3x2 grid
// You can add event listeners or other logic to dynamically call `updateGridLayout` based on user interactions
});
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
#grid-container {
display: grid;
gap: 10px;
width: 100%;
max-width: 600px;
}
.grid-item {
background-color: #4CAF50;
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100px;
display: none; /* Hide all items by default */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Grid</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
<script src="script.js"></script>
</body>
</html>
HTML:#grid-container 包含 6 个带有 grid-item 类的 div 元素。 CSS:#grid-container 使用 CSS 网格布局,项目之间有间隙。每个网格项都有一个基本的可见性样式。 JavaScript:
updateGridLayout 函数获取所选项目的数量 (selectionCount) 并相应地调整网格布局。 它根据选择计数计算列数,最多 3 列。 它更新网格容器的 gridTemplateColumns 属性来调整列布局。它根据选择计数显示或隐藏每个网格项目。 您可以使用不同的数字调用 updateGridLayout 函数来查看布局如何变化。在真实的应用程序中,您将根据用户交互调用此函数,例如复选框选择或其他输入方法。