Hiding the mouse cursor when idle using JavaScript

后端 未结 7 1946
灰色年华
灰色年华 2021-02-14 01:29

Is it possible to use JavaScript to set the cursor attribute to the property none if the mouse is inactive for a certain amount of time (say, five seco

7条回答
  •  轮回少年
    2021-02-14 02:18

    The following works for me in Firefox 3.6.13 so long as the cursor is over an actual element that doesn't have a non-default cursor (so it doesn't work if the cursor is over a form element or link, for example), although in general I recommend against doing this, because it is non-standard and extremely poor usability.

    Aside: It's more compatible not to use querySelector() when there's an alternative, such as document.body or document.getElementById().

    (function() {
        var mouseTimer = null, cursorVisible = true;
    
        function disappearCursor() {
            mouseTimer = null;
            document.body.style.cursor = "none";
            cursorVisible = false;
        }
    
        document.onmousemove = function() {
            if (mouseTimer) {
                window.clearTimeout(mouseTimer);
            }
            if (!cursorVisible) {
                document.body.style.cursor = "default";
                cursorVisible = true;
            }
            mouseTimer = window.setTimeout(disappearCursor, 5000);
        };
    })();
    

提交回复
热议问题