0

我正在制作一个待办事项列表,当我将鼠标悬停在对应的李上时,我有一个显示(它增加不透明度)删除按钮的功能。

  todosUl.addEventListener("mouseover", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity=1;
  });
  todosUl.addEventListener("mouseout", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity = 0;
  });

问题是,每当我接近按钮区域时,按钮就会再次消失。发生这种情况时,控制台会显示:Cannot read property 'style' of null

这就是我创建 Li 的方式:

todoLi.appendChild(view.createDeleteButton(position));

createDeleteButton: function (liId) {
    var deleteButton = document.createElement('button');
    deleteButton.textContent = 'X';
    deleteButton.className = 'deleteButton';
    deleteButton.id = 'deleteButton'+liId;
    return deleteButton;
4

2 回答 2

1

您需要 js 进行此渲染的任何特殊原因?下面是一个 html/css 模型

.delete {
  opacity: 0;
}
li:hover > .delete {
  opacity: 1;
}
<ul id="toDos">
  <li>To Do Item 1<input type="button" class="delete" value="Delete"/></li>
  <li>To Do Item 2<input type="button" class="delete" value="Delete"/></li>
  <li>To Do Item 3<input type="button" class="delete" value="Delete"/></li>
  <li>To Do Item 4<input type="button" class="delete" value="Delete"/></li>
</ul>

于 2020-01-29T22:45:13.057 回答
0

我建议使用mouseenterandmouseleave而不是mouseoverandmouseout事件。

var todosUl = document.getElementById("todoitem1");
todosUl.addEventListener("mouseenter", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity=1;
  });
  todosUl.addEventListener("mouseleave", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity = 0;
  });
<div id='todoitem1' width='100%' style='background-color: yellow'>
  <button id="deleteButtontodoitem1" style='opacity: 0'>Delete</button>
</div>

于 2020-01-29T22:37:45.280 回答