javascript - Angular:样式或类绑定、座位图
问题描述
我正在为我的研究生学习项目而苦苦挣扎。我需要在 Angular 中制作交互式座位图,最多选择 9 个座位。在浏览了我以前的课程后,我能够在 JS 中创造一些魔法,但没有最大选择(链接到下面的 codepen)。
HTML 代码包含巨大的 SVG 图形 - 您可以在下面附加的 codepen 中找到它
CSS
.occupied {
fill: red;
}
.free {
fill: #afafaf;
}
Javascript
const buttonArray = document.querySelectorAll("#seats path");
console.log("query", typeof buttonArray);
var myArray = Array.from(buttonArray);
console.log(myArray);
for (let i = 0; i < myArray.length; i++) {
myArray[i].setAttribute("id", `seat_${i + 1}`);
document.getElementById(`seat_${i + 1}`).addEventListener("click", function() {
if (document.getElementById(this.id).getAttribute("class") == "occupied") {
document.getElementById(this.id).removeAttribute("style");
document.getElementById(this.id).setAttribute("class", "free");
} else {
document.getElementById(this.id).removeAttribute("style");
document.getElementById(this.id).setAttribute("class", "occupied");
}
});
}
我不知道如何在 Angular 中实现它,或者如何让它更简单。当然还有如何选择最多 9 个座位。
我将不胜感激您的任何建议和帮助。
解决方案
您可以将 onClick 功能添加到 path=seats
<g id="seats" (click)="onClick($event)">
然后使用closest
方法获取座位,它被点击了。在您的示例中,所有座位路径都有 class st121
。这意味着我们可以坐下来$event.target.closest('.st121');
对于最大座位,您可以添加一个柜台并注意它。
import {
Component,
OnInit
} from '@angular/core';
const MAX_SEATS = 9;
@Component({
selector: 'app-seatmap',
templateUrl: './seatmap.component.html',
styleUrls: ['./seatmap.component.css']
})
export class SeatmapComponent implements OnInit {
constructor() {}
ngOnInit() {}
counter = 0;
onClick($event) {
const seat = $event.target.closest('.st121');
if (!seat) {
return;
}
const res = seat.getAttribute("class").split(' ').indexOf('occupied');
if (res > -1) {
seat.removeAttribute("style");
seat.setAttribute("class", "free st121");
this.counter -= 1;
} else if (this.counter < MAX_SEATS) {
seat.removeAttribute("style");
seat.setAttribute("class", "occupied st121");
this.counter += 1;
}
}
}
推荐阅读
- docker - 如何在 Docker ps status column/custome column 下暴露 Docker 镜像中运行的所有服务的状态
- reportlab - 是否可以将阴影/衬线样式应用于reportLab表格单元格
- java - apache.commons.logging classNotFound 即使添加了对 Maven 的依赖
- arrays - 从 Yelp Api 获取信息
- macos - macOS 11.5.2。更改代码后,我必须重置程序的隐私
- wordpress - 创建没有 SSL 的单页 WordPress
- android - 如何在 Android 中启用对不可变对象的增量注释处理器支持
- python - 在逻辑回归中强制使用二元系数
- reactjs - 如何在堆叠条之间添加间隙
- ios - 在 iOS 中打开应用时显示本地通知