我知道你不想要一个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);}
}