Javascript / css / html - 防止mousedown禁用悬停

时间:2017-05-26 15:49:21

标签: javascript html css hover

似乎在浏览器中,鼠标按下时会禁用鼠标悬停事件,如下例所示:(无需查看代码,只需运行示例查看我在说什么。)< / p>

* { user-select: none; }
#click, #drag, #hover {
  position: absolute;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 4px rgba(0, 0, 0, 0.3);
  text-align: center;
  color: #ffffff;
  cursor: default;
}
#click {
  width: 150px; height: 150px; line-height: 150px;
  left: 10px; top: 50%; margin-top: -75px;
  background-color: #d00000;
}
#drag {
  width: 220px; height: 50px; line-height: 50px;
  left: 160px; top: 50%; margin-top: -25px;
  background-color: #900000;
}
#hover {
  width: 200px; height: 200px; line-height: 200px;
  left: 380px; top: 50%; margin-top: -100px;
  background-color: #000000;
  white-space: nowrap;
}
#hover:after {
  content: "This element has hover effects";
  position: absolute;
  display: inline-block;
  color: #909090;
  left: 5px; top: -80px;
  font-size: 11px;
}
#hover:hover {
  background-color: #ffffff;
  color: #000000;
}
<div id="click">
  Click down here
</div>
<div id="drag">
  --> Now drag over this way -->
</div>
<div id="hover">
  No hover occurs
</div>

请注意,释放鼠标按钮的那一刻,悬停事件通常会发生在最右侧的div上。

如何在按住鼠标时允许在任何元素上发生悬停事件?在css,纯javascript或html中寻找解决方案。

1 个答案:

答案 0 :(得分:1)

没有一种纯粹的CSS方法可以解决这个问题,因为这是它的工作原理。没有多少方法可以用CSS覆盖那些东西。

您需要做的是使用mouseenter和/或mouseover以及mouseout和/或mouseleave手动实施您自己的悬停功能。

这样的事情:

const myElement = document.querySelector('#myElement');

myElement.addEventListener('mouseenter', ({ target }) => target.classList.add('hovering'));
myElement.addEventListener('mouseleave', ({ target }) => target.classList.remove('hovering'));
div {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  background: #F00;
}

div.hovering {
  background: #0F0;
}
<div id="myElement"></div>

相关问题