【发布时间】:2023-02-07 06:41:06
【问题描述】:
我有一个列表,其中包含几个类 (.box) 的框,这些框不能有 id 属性,当将鼠标悬停在它们上方时,它将显示删除按钮 (#btnDel) 以删除元素,问题是:如何选择这个悬停的元素,删除按钮是一个特定的元素,但是这个元素没有id属性,我该如何选择(文档.....)?
将鼠标悬停在 div.box 上时,显示删除按钮并包含 onclick=deleteElem('?') 函数以删除特定的 div.box。
const list = document.getElementById('list');
//--Select Delete Button id(btnDel) --//
const btnDel = document.getElementById('btnDel');
list.addEventListener('mouseenter', e => {
if (e.target.matches('.box')) {
//-- coordinates ---//
let rect = e.target.getBoundingClientRect();
//-- Show Delete Button --//
btnDel.style.top = rect.top + 'px';
btnDel.style.display = 'block';
//- How to Delete Element that has no ID? Is there another way to Select the Element Mouse Hover class(.box) ? -- ///
btnDel.setAttribute('onclick', "deleteElem('?')");
}
}, true);
function deleteElem(id) {
var elem = document.getElementById(id);
elem.remove();
}
#list {
max-width: 200px;
}
#list div {
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
margin: 10px;
font-weight: 600;
}
#btnDel {
cursor: pointer;
position: absolute;
display: none;
left: 204px;
}
#btnDel div {
background-color: #ffdfdf;
padding: 7px;
border-radius: 7px;
color: red;
font-size: 15px;
}
<div id="list">
<div class="box">Box 01</div>
<div class="box">Box 02</div>
<div class="box">Box 03</div>
<div class="box">Box 04</div>
<div class="box">Box 05</div>
</div>
<div id="btnDel">
<div>
(X) Delete
</div>
</div>
【问题讨论】:
-
您可以在鼠标悬停事件中访问
e.target以传递给按钮。您可以将deleteElem函数转换为(target) => () => target.remove()形式的生成器
标签: javascript