简体   繁体   English

当我失去对输入元素的关注时,如何检查鼠标是什么元素

[英]How to check over what element my mouse is when I lose focus on input element

Let's say I have this: 假设我有这个:

<body>
<input type="text" onblur="myFunction()" />

<... rest of page ...>

</body>


<script type="text/javascript">

    function myFunction()
    {
        //this function alerts over what element your mouse is when the input loses focus
    }
</script>

Does someone know how to implement this? 有人知道如何实现吗?

You could track what element your mouse if hovering over, like this: 您可以跟踪鼠标悬停在哪个元素上,如下所示:

<input type="text" id="myInput" onblur="myFunction()" />
var input = document.getElementById('myInput'), // Get the input element
    focus;

input.onmouseover = input.onfocus = function(){focus = true;}; // Set focus to true if the input gains focus
input.onmouseout = input.onblur = function(){focus = false}; // Set focus to false if the input loses focus

document.body.onmousemove = function(e){
    if(!focus){ // Only log the target is the input doesn't have focus
        console.log(e.target); //Log the current element the mouse is hovering over.
    }
};

As far as I know, there's no accurate way to check the mouse's current target on the "mouseleave" or "blur" events, since the event.target of those functions will point to the element the mouse just left, not to the element the mouse is currently hovering over. 据我所知,没有准确的方法来检查"mouseleave""blur"事件上鼠标的当前目标,因为这些函数的event.target将指向鼠标刚离开的元素,而不是指向鼠标当前正在悬停。

Edit: 编辑:
I added some code so it only logs when the input doesn't have focus. 我添加了一些代码,因此仅在输入没有焦点时才记录日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM