js盒子内的子元素盒子点击移动到另一个盒子代码
时间: 2023-05-29 16:06:06 浏览: 162
以下是一个简单的示例代码,当点击一个盒子内的子元素盒子时,它会移动到另一个盒子中:
HTML代码:
```html
<div class="box1">
<div class="child-box"></div>
</div>
<div class="box2"></div>
```
CSS代码:
```css
.box1 {
width: 200px;
height: 200px;
background-color: yellow;
position: relative;
}
.child-box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.box2 {
width: 200px;
height: 200px;
background-color: green;
margin-top: 20px;
}
```
JavaScript代码:
```javascript
const childBox = document.querySelector('.child-box');
const box2 = document.querySelector('.box2');
childBox.addEventListener('click', () => {
box2.appendChild(childBox);
});
```
解释:
首先,我们获取了两个盒子元素 `box1` 和 `box2`,以及要移动的子元素盒子 `child-box`。
然后,我们添加了一个点击事件监听器到 `child-box` 元素上,当它被点击时,我们使用 `appendChild()` 方法将它移动到 `box2` 中。
`appendChild()` 方法可以将一个元素插入到另一个元素的子元素列表的末尾。在这个例子中,我们将 `child-box` 元素插入到 `box2` 元素中,这样它就被移动到了另一个盒子中。