【发布时间】:2018-12-07 22:04:57
【问题描述】:
我有一个<ul> 列表,其中包含一些<input> 字段,我需要在鼠标上显示<span class="delete-link"> 元素在实际字段上。
当用户点击X关闭按钮时,从列表中隐藏当前<li>元素。
我正在尝试使用 vanilla JavaScript 来做到这一点,但我被困在了这一点上。无论我将鼠标悬停在哪个字段中,我的代码都只显示第一个关闭按钮。
HTML
<ul class="social-links-list">
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link" onclick=''>X</span>
</li>
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link">X</span>
</li>
<li class="social-link">
<input type="text" name="" id="" placeholder="http://facebook.com/id">
<span class="delete-link">X</span>
</li>
</ul>
CSS
ul {
list-style: none;
}
input[type='text'] {
height: 1rem;
padding: 0.5rem;
margin-bottom: 1rem;
border-radius: 3px;
border: 1px solid #ccc;
}
.delete-link {
color: red;
opacity: 0;
cursor: pointer;
}
JS
var socialField = document.querySelectorAll('.social-link');
socialField.forEach(function(el) {
el.addEventListener('mouseover', function(){
closeBtn.style.opacity = 1;
});
el.addEventListener('mouseout', function(){
closeBtn.style.opacity = 0;
});
var closeBtn = document.querySelector('.social-link .delete-link');
for (i = 0; i < closeBtn.length; i++) {
closeBtn[i].addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
}
});
检查这个JSFiddle。
【问题讨论】:
-
创建获取项目ID的函数。然后单击调用该函数。所以你可以删除那个项目。
标签: javascript html css events dom