前端小案例——购买电影票(HTML+CSS+JS, 附源码)座位不固定
时间: 2024-09-20 12:13:23 浏览: 39
前端小案例:创建一个简单的电影票购买页面,我们可以使用HTML、CSS和JavaScript来实现。这个例子将展示如何动态生成座位选择区域,并且座位不是固定的。首先,我们会构建基础结构,然后添加座位布局以及交互功能。
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>电影票购买</title>
<style>
.seat-container {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 20px;
padding: 20px;
}
.seat {
width: 60px;
height: 40px;
background-color: #ccc;
border-radius: 5px;
margin-bottom: 10px;
cursor: pointer;
user-select: none;
}
.selected {
background-color: green;
}
</style>
</head>
<body>
<h1>电影票购买</h1>
<div class="seat-container" id="seatContainer"></div>
<button onclick="addSeat()">增加座位</button>
<button onclick="removeSeat()">减少座位</button>
<p>已选座位: <span id="selectedSeats">0</span>/ 总座位数: <span id="totalSeats">20</span></p>
<script>
const seatCount = 20;
let seats = Array(seatCount).fill().map(() => '未选');
const seatContainer = document.getElementById('seatContainer');
const selectedSeats = document.getElementById('selectedSeats');
const totalSeats = document.getElementById('totalSeats');
function addSeat() {
if (seats.length < seatCount) {
seats.push('未选');
createSeats();
selectedSeats.textContent = seats.filter(s => s === '已选').length;
}
}
function removeSeat() {
if (seats.length > 0) {
seats.pop();
createSeats();
selectedSeats.textContent = seats.filter(s => s === '已选').length;
}
}
function createSeats() {
seatContainer.innerHTML = '';
seats.forEach((status, index) => {
const seat = document.createElement('div');
seat.classList.add('seat', status === '已选' ? 'selected' : '');
seat.innerText = `${index + 1}`;
seat.addEventListener('click', () => toggleSeat(index));
seatContainer.appendChild(seat);
});
}
function toggleSeat(index) {
seats[index] = seats[index] === '已选' ? '未选' : '已选';
createSeats();
}
</script>
</body>
</html>
```
在这个案例中,我们创建了一个网格布局的座位容器,每个座位是一个可点击元素。当用户点击座位时,`toggleSeat`函数会切换座位状态。点击“增加座位”按钮会添加新的空位,而“减少座位”按钮会移除最后一个已被选中的座位。
阅读全文