How can I determine start and stop points for mouse cursor?

半腔热情 提交于 2019-12-24 11:04:17

问题


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 ?

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

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

Thank you.


回答1:


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>



回答2:


The start location is the location when the mousemove event is first fired. It will keep firing until the mouse stops moving. So, if you add a timer (setTimeout/clearTimeout) to your mousemove event function, you can say the mouse has stopped moving after a certain amount of time has passed without the mousemove function being called.



来源:https://stackoverflow.com/questions/7265076/how-can-i-determine-start-and-stop-points-for-mouse-cursor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!