当元素高于目标元素时,鼠标悬停不起作用

时间:2018-01-19 15:35:17

标签: javascript html

我正在学习鼠标事件。目前,我的目标是2 images on top of each other。例如,将鼠标移到图像上并看到弹出窗口。当你移开鼠标时,弹出窗口就会移动。我认为这是很常见的事情。

因为我的图像在另一张面前,我的研究表明我需要使用mouseleave

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out

我遇到的问题是,当我试图隐藏或删除隐藏类(使图像可见或不可见)时,我会产生闪烁效果。

此代码段显示了所有内容



var inst = document.getElementById("instrument");
inst.addEventListener("mouseover", function() {
  toggleEdit(true);
})
inst.addEventListener("mouseleave", function() {
  toggleEdit(false);
})
var edit = document.getElementById("edit");
var i = 0;

function toggleEdit(isShow) {
  console.log(i++);
  edit.className = edit.className.replace(" hide", "");

  if (!isShow) {
    edit.className += " hide";
  }
}

.parent {
  position: relative;
  margin-left: 40%;
  background: green;
}

.image1 {
  position: absolute;
  top: 0;
  left: 0;
}

.image2 {
  position: absolute;
  top: 0px;
}

.image2 img {
  max-width: 20px;
}

.hide {
  visibility: hidden;
  display: block;
}

<div class="parent">
  <img class="image1" src="https://placehold.it/100" id="instrument" />
  <a id="edit" href="#" class="image2 hide"><img src="https://cdn.pixabay.com/photo/2017/06/06/00/33/edit-icon-2375785_960_720.png" /></a>
</div>
&#13;
&#13;
&#13;

JSFIDDLE

如何防止这种闪烁?

2 个答案:

答案 0 :(得分:4)

你根本不需要JS。只需使用:hover

的CSS即可实现

.parent {
  position: relative;
  margin-left: 40%;
  background: green;
}
.parent:hover .image2{
    visibility: visible
}

.image1 {
  position: absolute;
  top: 0;
  left: 0;
}

.image2 {
  position: absolute;
  top: 0px;
  visibility: hidden;
}

.image2 img {
  max-width: 20px;
}
<div class="parent">
  <img class="image1" src="https://placehold.it/100" id="instrument" />
  <a id="edit" href="#" class="image2">
    <img src="https://cdn.pixabay.com/photo/2017/06/06/00/33/edit-icon-2375785_960_720.png" />
  </a>
</div>

答案 1 :(得分:-1)

这对我来说似乎是预期的行为。一旦你将鼠标悬停在小图像上,理论上它就不会超过大图像,这就是小图像消失的原因。当发生这种情况时,鼠标悬停效果会在大图像上再次触发,将其置于“循环”中。您可以为小图像添加相同的逻辑以及解决问题,但如上所述,更简单的方法是使用css。

var inst2 = document.getElementById("edit");
inst2.addEventListener("mouseover", function(){toggleEdit(true);})
inst2.addEventListener("mouseleave", function(){toggleEdit(false);})