如何检查我的鼠标是什么元素,当我失去了输入元素的焦点



我们设这个:

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

有人知道如何实现这个吗?

您可以跟踪鼠标悬停在哪个元素上,像这样:

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

据我所知,在"mouseleave""blur"事件上没有准确的方法来检查鼠标当前的目标,因为这些函数的event.target将指向鼠标刚刚离开的元素,而不是鼠标当前悬停在上面的元素。

编辑:


我添加了一些代码,所以它只记录当输入没有焦点。

最新更新