javascript 没有 jquery 我需要找出鼠标是否在一个元素上,而不是确定它何时结束(以防它不移动以触发 onmouseover)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18320190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
without jquery i need to find out if the mouse is over an element, not determine when it becomes over (in case it doesn't move to trigger onmouseover)
提问by Kender
without jquery
没有jQuery
basically what I am looking for is the ability to see if the mouse is over a div when a countdown finishes
基本上我正在寻找的是能够在倒计时完成时查看鼠标是否在 div 上
if the user is over the div then perform action for that div
如果用户在 div 上,则对该 div 执行操作
onmouseoveronly triggers when the mouse crosses the threshold of the div, if the mouse hasn't moved it wouldn't trigger, so that wouldn't work
onmouseover仅在鼠标越过 div 的阈值时触发,如果鼠标没有移动则不会触发,因此不起作用
I need to determine if the mouse is currently over a div at a specific point in time, if it has moved or not from the starting point
我需要确定鼠标当前是否在特定时间点位于 div 上,它是否已从起点移动
all of my hunting has only found onmousover, and nothing to see if the mouse just happens to be there to begin with
我所有的狩猎都只找到了onmousover,并没有看到老鼠是否刚好在那里开始
I don't have the javascript skills to determine overall coords of div, then map mouse coords and see if it fits there... which is what I believe I need to do
我没有 javascript 技能来确定 div 的整体坐标,然后映射鼠标坐标并查看它是否适合那里......这就是我认为我需要做的
采纳答案by km6zla
set a flag to true onmouseover and to false onmouseleave. when countdown finishes if flag is true then it is over element.
将标志设置为 true onmouseover 和 false onmouseleave。当倒计时结束时,如果 flag 为真,则元素结束。
HTML
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
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);
}
}
回答by rink.attendant.6
After reading the second answer (the one with millions of aelements) on this SO question, I've came up with this method works without moving the mouse on page load, without involving millions of elements.
在阅读了a关于这个 SO question的第二个答案(有数百万个元素的答案)后,我想出了这种方法,无需在页面加载时移动鼠标,也无需涉及数百万个元素。
HTML
HTML
<div id=t></div>
CSS
CSS
#t {
/* for illustrative purposes */
width: 10em;
height: 5em;
background-color: #0af;
}
#t:hover {
border-top-style: hidden;
}
JavaScript
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);
As stated earlier, bind to the finish event of your countdown instead of the clickevent on the document.
正如前面所述,绑定到你的倒计时的结束,而不是事件的click有关情况document。
You may also use any CSS style that's changed on :hover, I chose border-top-style as it is conspicuous. If you're using a border, choose something else.
您也可以使用任何更改过的 CSS 样式:hover,我选择了 border-top-style,因为它很显眼。如果您使用边框,请选择其他内容。
Here's a jsFiddle.
这是一个jsFiddle。
回答by Tim Mac
Just want to say that, I think jQuery's mouseenterand mouseleaveevents would make this a lot easier, but if you can't use them, maybe this will help you.
只想说,我认为 jQuerymouseenter和mouseleave事件会让这变得容易很多,但如果你不能使用它们,也许这会对你有所帮助。
Depending on how your page is laid out, this may not be too difficult. You can get the position of your element using the following. Quoting from another answer
根据页面的布局方式,这可能不会太难。您可以使用以下方法获取元素的位置。引用另一个答案
element.offsetLeftandelement.offsetTopare the pure javascript properties for finding an element's position with respect to its offsetParent; being the nearest parent element with a position of relative or absolute
element.offsetLeft和element.offsetTop是用于查找元素相对于其 offsetParent 的位置的纯 javascript 属性;是最近的具有相对或绝对位置的父元素
So, if your element is positioned relatively to the body, so far so good (We don't need to adjust anything).
因此,如果您的元素相对于 定位body,那么到目前为止很好(我们不需要调整任何内容)。
Now, if we attach an event to the documentmousemove event, we can get the current coordinates of the mouse:
现在,如果我们为documentmousemove 事件附加一个事件,我们可以获得鼠标的当前坐标:
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
}, false);
Now we just need to determine if the mouse falls within the element. To do that we need the height and width of the element. Quoting from another answer
现在我们只需要确定鼠标是否落在元素内。为此,我们需要元素的高度和宽度。引用另一个答案
You should use the
.offsetWidthand.offsetHeightproperties. Note they belong to the element, not .style.
您应该使用
.offsetWidth和.offsetHeight属性。注意它们属于元素,而不是 .style。
For example:
例如:
var element = document.getElementById('element');
var height = element.offsetHeight;
var width = element.offsetWidth;
Now we have all the information we need, and just need to determine if the mouse falls within the element. We might use something like this:
现在我们有了我们需要的所有信息,只需要确定鼠标是否落在元素内。我们可能会使用这样的东西:
var onmove = function(e) {
var minX = element.offsetLeft;
var maxX = minX + element.offsetWidth;
var minY = element.offsetTop;
var maxY = minY + element.offsetHeight;
if(e.clientX >= minX && e.clientX <= maxX)
//good horizontally
if(e.clientY >= minY && e.clientY <= maxY)
//good vertically
}
回答by Scott Mermelstein
Look into document.elementFromPoint. When you pass an x,yto elementFromPoint, it will return whatever element (or <body>, if no other specific element) is at that point. You can easily check if this element is the element you want.
查看document.elementFromPoint。当您传递x,yto 时elementFromPoint,它将返回此时的任何元素(或者<body>,如果没有其他特定元素)。您可以轻松检查此元素是否是您想要的元素。
The problem then is finding out what point your mouse is at. How to get the mouse position without events (without moving the mouse)?seems to say - don't. At least use mouseMove to track the cursor. The linked question gives examples of how to do so. (Look to the lower scoring answers, as the higher ones only got points for being snarky.)
然后的问题是找出您的鼠标所在的点。 如何在没有事件的情况下获取鼠标位置(不移动鼠标)?似乎在说——不要。至少使用 mouseMove 来跟踪光标。链接的问题给出了如何这样做的例子。(看看得分较低的答案,因为得分较高的答案只会因为狡猾而得分。)
回答by rink.attendant.6
This code works, but the mouse has to be moved once after page load.
此代码有效,但在页面加载后必须移动鼠标一次。
var coords;
var getMouseCoordinates = function (e) {
'use strict';
return {
x: e.clientX,
y: e.clientY
};
};
document.addEventListener('mousemove', function (e) {
coords = getMouseCoordinates(e);
}, false);
document.addEventListener('click', function () {
var divCoords = document.getElementById('t').getBoundingClientRect();
if (coords.x >= divCoords.left && coords.x <= divCoords.right && coords.y >= divCoords.top && coords.y <= divCoords.bottom) {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
You wouldn't bind to the clickevent of document, but rather the finish event of your countdown.
您不会绑定到 的click事件document,而是绑定到倒计时的完成事件。
Here's an example. Try clicking in the output window.
这是一个例子。尝试在输出窗口中单击。

