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

新手上路,请多包涵

没有jquery

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

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

onmouseover 只在鼠标越过div的阈值时触发,如果鼠标没有移动就不会触发,所以不行

我需要确定鼠标当前是否在特定时间点位于 div 上,是否已从起点移动

我所有的搜索都只找到了 onmousover ,没有看到鼠标是否刚好开始

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

原文由 Kender 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 249
2 个回答

将标志设置为 true onmouseover 和 false onmouseleave。当倒计时结束时,如果标志为真,则元素结束。

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>

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);
    }
}

原文由 km6zla 发布,翻译遵循 CC BY-SA 3.0 许可协议

在阅读了关于 这个 SO 问题的 第二个答案(包含数百万个 a 元素的答案)后,我想出了这种方法,无需在页面加载时移动鼠标,也无需涉及数百万个元素。

HTML

 <div id=t></div>

CSS

 #t {
    /* for illustrative purposes */
    width: 10em;
    height: 5em;
    background-color: #0af;
}
#t:hover {
    border-top-style: hidden;
}

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);

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

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

这是一个 jsFiddle

原文由 rink.attendant.6 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题