本文介绍了如何确定鼠标光标的起点和终点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设用户开始移动鼠标并停在浏览器的某个位置。如何使用Javascript / Jquery确定起点和终点?

Let's say the user starts to move mouse and stop at somewhere on the browser. How can I determine start and stop point with Javascript/Jquery ?

起点很简单,我可以通过mousemove事件得到它但是停止点怎么样?

Start point is easy, I can get it with mousemove event but what about stop point ?

我无法使用mouseenter或mouseleave事件,因为我的游乐场是窗口或文档本身。

I can't use mouseenter or mouseleave events because my playground is window or document itself.

谢谢。

推荐答案

使用setTimeout和clearTimeout的组合。
如果用户没有移动x秒,那就意味着他停了。

using a combination of setTimeout and clearTimeout.If the user doesn't move for x amount of seconds then it means that he stopped.

这里我给你写了一个例子:

Here I wrote you an example:

<script type="text/javascript">
    var lastMove = 0;
    var lastTimeout = 0;
    jQuery(document).ready(function () {
        $(document).mousemove(function (e) {
            $('#status').html(e.pageX + ', ' + e.pageY);
            var currentMove = (new Date()).getTime();
            if (lastTimeout != 0) {
                clearTimeout(lastTimeout);
            }
            if (currentMove - lastMove > 1500)
            { alert('started'); }
            lastMove = currentMove;
            lastTimeout = setTimeout(function () {
                var currentMove = (new Date()).getTime();
                if (currentMove - lastMove > 1500)
                { alert('stopped'); }
            }, 1510);
        });
    })
</script>
<h2 id="status">
0, 0
</h2>

这篇关于如何确定鼠标光标的起点和终点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 16:42