0

我处于不能简单地使用悬停事件的位置,但是当鼠标位于给定元素的区域内以及离开该区域时,我需要触发 mouseover 和 mouseout。它可以是 javascript、jquery 或混合。我还没有成功地将鼠标位置存储为变量或找出一种方法来判断鼠标何时离开给定区域。我的每个问题都由'????'表示 在代码中。

function targetMouse() {
    var box = document.getElementById('CleanBox'),
        top = box.offsetTop,
        left = box.offsetLeft,
        right = left + box.offsetWidth,
        bottom = top + box.offsetHeight,
        mouseX = ????;
        mouseY = ????;

    if (left < mouseX > right && top < mouseY > bottom) {
        $('#CleanBox').mouseover();
    }
    else if (????) {
        $('#CleanBox').mouseout();
    }
}

谢谢您的帮助!

4

1 回答 1

1

像这样的东西?

。盒子 {

    width:300px;
    height:100px;
    position: absolute;
    top: 30%;
    left: 30%;
    background-color:yellow;
    border:2px solid;
}

<div id="popup">Mouse is on box</div>
<div id="box" class="box"></div>

var box = document.getElementById("box");
var top = box.offsetTop;
var left = box.offsetLeft;
var right = left + box.offsetWidth;
var bottom = top + box.offsetHeight;
var hoverState = false;
var popup = document.getElementById("popup");

popup.hidden = true;

function hoverCheck(evt) {
    var x = evt.clientX;
    var y = evt.clientY;

    if (x >= left && x <= right && y >= top && y <= bottom) {
        if (hoverState === false) {
            hoverState = true;
            console.log("mouseon");
        }
    } else {
        if (hoverState === true) {
            hoverState = false;
            console.log("mouseoff");
        }
    }

    popup.hidden = !hoverState;
}

document.addEventListener("mousemove", hoverCheck, false);

jsfiddle上

于 2013-04-21T09:40:14.913 回答