【问题标题】:Triggering :hover on moving element without moving mouse触发:悬停在移动元素上而不移动鼠标
【发布时间】:2019-01-12 11:03:06
【问题描述】:

#box {
  animation: scroll 2s linear infinite;
  width: 100px;
  height: 100px;
  background: red;
}

#box:hover {
  background: green;
}

@keyframes scroll {
  from {transform: none;}
  to {transform: translateX(400px);}
}
<div id="box"></div>

如果您将鼠标悬停在该框上,并且之后不移动鼠标,它会保持绿色。如果您将鼠标放在它的路径上并且不移动,它不会触发悬停。

在这种情况下,有没有办法在不移动鼠标的情况下触发悬停?

编辑:不使用 JavaScript。

【问题讨论】:

标签: html css hover mousemove onmousemove


【解决方案1】:

我知道您不需要 javascript 解决方案。但是,我不确定没有它是否有解决方案。当鼠标什么都不做时,您不能触发鼠标事件。

与此同时,我添加了一个使用 javascript 的解决方案,因为它可以帮助其他人使用 javascript 解决方案搜索答案并解决这个问题。

鼠标移动时的最后坐标存储为变量 x 和 y。使用Element.getBoundingClientRect()可以随时找到盒子的坐标。查看鼠标指针是否位于框内的功能可以设置为以任何选定的时间间隔运行。这将根据每种情况进行调整。

唯一的问题是打开此页面时鼠标根本没有移动。

var x = 0;
var y = 0;
var box = document.querySelector("#box");
document.onmousemove = function(e){
    x = e.pageX;
    y = e.pageY;
}
setInterval(findMouse, 50);
function findMouse(){
    // Looking for the updated coordinates of the box
    var movingBox = box.getBoundingClientRect();

    if( x>=movingBox.left && x<=movingBox.right
            && y>=movingBox.top && y<=movingBox.bottom)
        document.getElementById("box").style.backgroundColor = "green";
    else
        document.getElementById("box").style.backgroundColor = "red";

}
#box {
	animation: scroll 2s linear infinite;
	width: 100px;
	height: 100px;
	background: red;
}

#box:hover {
	background: green;
}

@keyframes scroll {
	from {transform: none;}
	to {transform: translateX(400px);}
}
&lt;div id="box"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2011-04-27
    • 2018-03-04
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 2013-07-02
    • 1970-01-01
    相关资源
    最近更新 更多