1.事件委托
1.1 概念
当页面元素不存在的时候,而此时想先给未知的元素绑定事件,但是单纯的绑定事件又不能触发,那是因为未找到的绑定的对象,所以此时你需要将事件委托给其祖先元素。
1.2 例子
//css部分
<link rel="stylesheet" href="https://www.bootcss.com/p/buttons/css/buttons.css">
<style>
.button {
margin-right: 10px;
}
</style>
//body内的内容
<body>
<div class="container">
<button class="button button-primary button-pill button-small">ADD a Button</button>
</div>
<script src="./js/jquery.js"></script>
<script>
$(".container").on("click", "button", function () {
let bt = $("<button/>").html("ADD a Button").addClass(
"button button-primary button-pill button-small");
$(".container").append(bt)
})
</script>
</body>
1.3 例子的运行结果
初始图
点击添加后的结果
2.简易版飞机大战小游戏
2.1 css代码
<style>
.container {
width: 500px;
height: 80vh;
margin: 10vh auto;
background-color: black;
position: relative;
overflow: hidden;
}
.plane {
width: 100px;
height: 50px;
/* background-color: red; */
position: absolute;
left: calc(50% - 40px);
bottom: 10px;
}
.bullet {
width: 20px;
height: 10px;
background-color: red;