js中点击空白页面生成一个div,再次点击删除第v
时间: 2024-05-10 20:20:16 浏览: 14
ar div元素
以下是一个实现该功能的代码示例:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>点击空白页面生成div</title>
<style>
#container {
height: 100vh;
background-color: lightgray;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
left: 0;
display: none;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="index.js"></script>
</body>
</html>
```
JavaScript:
```js
const container = document.querySelector('#container');
let box;
container.addEventListener('click', e => {
// 判断点击的是否是空白区域
if (e.target === container) {
// 如果已经存在box,则删除box
if (box) {
box.remove();
box = null;
} else {
// 否则创建box并添加到container中
box = document.createElement('div');
box.classList.add('box');
container.appendChild(box);
}
}
});
```
首先通过 `document.querySelector` 方法获取页面中的 `#container` 元素,然后给它添加一个点击事件监听器。在监听器中,首先判断点击的是否是空白区域,如果是,则判断是否已经存在 `box` 元素。如果已经存在,则删除 `box` 元素并将 `box` 变量设为 null;如果不存在,则创建一个 `box` 元素,并添加到 `container` 中。最后,通过 `element.remove` 方法删除 `box` 元素。