如何使用CSS和JavaScript创建列表网格视图?
要创建列表网格视图,代码如下-
示例
<!DOCTYPE html><html>
<head>
<style>
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
/*创建两个相等的列,它们彼此相邻浮动 */
.column {
float: left;
width: 50%;
padding: 10px;
color: white;
}
/*清除列后的浮动*/
.row:after {
content: "";
display: table;
clear: both;
}
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 12px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.btn:hover {
background-color: #ddd;
}
.btn.active {
background-color: #666;
color: white;
}
</style>
</head>
<body>
<h1>List Grid view example</h1>
<h2>Click on the below buttons to switch views</h2>
<div id="btnContainer">
<button class="btn" onclick="listView()">List</button>
<button class="btn active" onclick="gridView()">Grid</button>
</div>
<br />
<div class="row">
<div class="column" style="background-color:rgb(154, 9, 173);">
<h2>Column 1</h2>
</div>
<div class="column" style="background-color:rgb(113, 35, 216);">
<h2>Column 2</h2>
</div>
</div>
<div class="row">
<div class="column" style="background-color:rgb(19, 143, 85);">
<h2>Column 3</h2>
</div>
<div class="column" style="background-color:rgb(207, 69, 27);">
<h2>Column 4</h2>
</div>
</div>
<script>
var elements = document.querySelectorAll(".column");
function listView() {
Array.from(elements).forEach(item => {
item.style.width = "100%";
});
Array.from(document.querySelectorAll(".btn")).forEach((item, index) => {
if (index === 0) item.classList.add("active");
else item.classList.remove("active");
});
}
function gridView() {
Array.from(elements).forEach(item => {
item.style.width = "50%";
});
Array.from(document.querySelectorAll(".btn")).forEach((item, index) => {
if (index === 1) item.classList.add("active");
else item.classList.remove("active");
});
}
</script>
</body>
</html>
输出结果
上面的代码将产生以下输出-
在单击列表按钮时-
以上是 如何使用CSS和JavaScript创建列表网格视图? 的全部内容, 来源链接: utcz.com/z/321481.html