没有jquery我需要找出鼠标是否在元素上,而不是确定它何时结束(如果它没有移动到触发onmouseover)

Ken*_*der 7 javascript

没有jquery

基本上我正在寻找的是能够在倒计时结束时查看鼠标是否超过div

如果用户在div上,则执行该div的操作

onmouseover 只有当鼠标超过div的阈值时才会触发,如果鼠标没有移动则不会触发,因此无效

我需要确定鼠标当前是否在特定时间点的div上,如果它已经从起点移动了

我的所有狩猎都只找到了onmousover,如果鼠标恰好在那里开始的话,没有什么可看的

我没有javascript技能来确定div的整体坐标,然后映射鼠标坐标,看它是否适合那里...这是我认为我需要做的

rin*_*t.6 13

这个SO问题a上阅读了第二个答案(有数百万个元素的答案)后,我想出了这个方法,无需在页面加载时移动鼠标,而不涉及数百万个元素.

HTML

<div id=t></div>
Run Code Online (Sandbox Code Playgroud)

CSS

#t {
    /* for illustrative purposes */
    width: 10em;
    height: 5em;
    background-color: #0af;
}
#t:hover {
    border-top-style: hidden;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript的

document.addEventListener('click', function () {
    var c = window.getComputedStyle(document.getElementById('t')).getPropertyValue('border-top-style');

    if (c === 'hidden') {
        alert('Mouse in box');
    } else {
        alert('Mouse not in box');
    }
}, false);
Run Code Online (Sandbox Code Playgroud)

如前所述,绑定到倒计时的结束事件而不是click事件document.

您也可以使用任何已更改的CSS样式:hover,我选择了border-top-style,因为它很显眼.如果您正在使用边框,请选择其他内容.

这是一个jsFiddle.


km6*_*zla 5

将标志设置为true onmouseover和false onmouseleave.当倒计时结束时,如果flag为true,那么它就是元素.

HTML

<div id="div-name">the section of the code i am working with has a countdown timer, when it reaches 0 i need to know if the mouse is over a specific box</div>
<button id="notification" onclick="javascript: letsCountIt(5);">click to start countdown</button>
Run Code Online (Sandbox Code Playgroud)

JS

window.ev = false;

document.getElementById('div-name').onmouseover = function () {
    window.ev = true;
    console.log(window.ev);
}

document.getElementById('div-name').onmouseout = function () {
    window.ev = false;
    console.log(window.ev);
}

window.letsCountIt = function (cdtimer) {
    cdtimer--;
    document.getElementById('notification').innerHTML = cdtimer;

    if (cdtimer == 0) {
        if (window.ev === true) {
            alert('over');
        } else {
            alert('not over');
        }
    } else {
        setTimeout(function(){letsCountIt(cdtimer);}, 1000);
    }
}
Run Code Online (Sandbox Code Playgroud)