空闲时使用 JavaScript 隐藏鼠标光标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3354239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:56:12  来源:igfitidea点击:

Hiding the mouse cursor when idle using JavaScript

javascriptcsscursormousemove

提问by u365975

Is it possible to use JavaScript to set the cursorattribute to the property noneif the mouse is inactive for a certain amount of time (say, five seconds) and set it back to autowhen it becomes active again?

如果鼠标在一段时间内(例如五秒)处于非活动状态,并在它再次变为活动状态时将其设置回,是否可以使用 JavaScript 将cursor属性设置为该属性?noneauto

EDIT:I realize that noneis not a valid value for the cursorproperty. Nonetheless, many web-browsers seem to support it. Furthermore, the primary user for this is myself, so there is little chance of confusion arising as a result.

编辑:我意识到这none不是该cursor财产的有效价值。尽管如此,许多网络浏览器似乎支持它。此外,此操作的主要用户是我自己,因此几乎不会出现混淆。

I've got two scripts that can do something similar:

我有两个脚本可以做类似的事情:

window.addEventListener("mousemove",
    function(){
        document.querySelector("#editor").style.background = "#000";
        setTimeout("document.querySelector('#editor').style.background = '#fff'", 5000);
    }
, true);

and

var timeout;
var isHidden = false;

document.addEventListener("mousemove", magicMouse);

function magicMouse() {
    if (timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
        if (!isHidden) {
            document.querySelector("body").style.cursor = "none";
            document.querySelector("#editor").style.background = "#fff";
            isHidden = true;
        }
    }, 5000);
    if (isHidden) {
        document.querySelector("body").style.cursor = "auto";
        document.querySelector("#editor").style.background = "#000";
        isHidden = false;
    }
};

With each of these, when the mouse is inactive for more than five seconds the background color turns white, and when the cursor is moved the background turns black. However, they don't work for making the cursor disappear. What surprises me is that if I put the command document.querySelector("body").style.cursor = "none";into the JavaScript console it works perfectly. Inside the scripts, it does not seem to work.

对于其中的每一个,当鼠标处于非活动状态超过 5 秒时,背景颜色变为白色,而当光标移动时,背景变为黑色。但是,它们不能使光标消失。令我惊讶的是,如果我将命令document.querySelector("body").style.cursor = "none";放入 JavaScript 控制台,它可以完美运行。在脚本内部,它似乎不起作用。

I've posted the above scripts as this is as far as I have come in getting this to work. I'm not necessarily asking for a fix for either of the scripts; if you know of a more efficient way of hiding the cursor, please share.

我已经发布了上述脚本,因为这是我开始使用它的范围。我不一定要求修复任何一个脚本;如果您知道隐藏光标的更有效方法,请分享。

回答by Joey

In CSS 2 noneis not a valid value for the cursorproperty. It is valid in CSS 3, however.

在 CSS 2none中不是cursor属性的有效值。但是,它在 CSS 3 中有效。

Otherwise you might be able to use a custom cursor loaded from a URI that is simply transparent.

否则,您可能能够使用从简单透明的 URI 加载的自定义游标。

I would consider this to be highly distracting for the user, though, so I wouldn't advise you to actually do that.

不过,我认为这会极大地分散用户的注意力,因此我不建议您实际这样做。

回答by Tim Down

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.

以下在 Firefox 3.6.13 中对我有用,只要光标位于没有非默认光标的实际元素上(因此,如果光标位于表单元素或链接上,则它不起作用,例如),虽然一般来说我不建议这样做,因为它是非标准的并且可用性极差。

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

旁白:querySelector()当有替代方案时不使用更兼容,例如document.bodydocument.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);
    };
})();

回答by cby016

This worked for me (taken from https://gist.github.com/josephwegner/1228975).

这对我有用(取自https://gist.github.com/josephwegner/1228975)。

Note reference to an html element with id wrapper.

注意对带有 id 包装器的 html 元素的引用。

//Requires jQuery - http://code.jquery.com/jquery-1.6.4.min.js
$(document).ready(function() { 


    var idleMouseTimer;
    var forceMouseHide = false;

    $("body").css('cursor', 'none');

    $("#wrapper").mousemove(function(ev) {
            if(!forceMouseHide) {
                    $("body").css('cursor', '');

                    clearTimeout(idleMouseTimer);

                    idleMouseTimer = setTimeout(function() {
                            $("body").css('cursor', 'none');

                            forceMouseHide = true;
                            setTimeout(function() {
                                    forceMouseHide = false;
                            }, 200);
                    }, 1000);
            }
    });
});

回答by Lovro

If anyone still looking for answer in 2019 (as did I), this approach works on FF 71 and Chrome 78:

如果有人在 2019 年仍在寻找答案(就像我一样),这种方法适用于 FF 71 和 Chrome 78:

var DEMO = {
  INI: {
    MOUSE_IDLE: 3000
  },
  hideMouse: function() {
    $("#game").css('cursor', 'none');
    $("#game").on("mousemove", DEMO.waitThenHideMouse);
  },
  waitThenHideMouse: function() {
    $("#game").css('cursor', 'default');
    $("#game").off("mousemove", DEMO.waitThenHideMouse);
    setTimeout(DEMO.hideMouse, DEMO.INI.MOUSE_IDLE);
  },
  showMouse: function() {
    $("#game").off("mousemove", DEMO.waitThenHideMouse);
    $("#game").css('cursor', 'default');
  },
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

It's simple and clear. This version uses DEMO.hideMouse()to start hiding mouse and DEMO.showMouse()to cancel the event. Change #gameto div of your choice ...

它简单明了。此版本用于DEMO.hideMouse()开始隐藏鼠标和DEMO.showMouse()取消事件。更改#game为您选择的 div ...

It's more clear to work with onand offswitch and named functions instead of lambdas.

使用onoff切换和命名函数而不是 lambda更清晰。

I know that OP didn't specify that answers using JQuery are expected, but in my experience: I am always happy to see different approaches to learn from.

我知道 OP 没有指定使用 JQuery 的答案是预期的,但根据我的经验:我总是很高兴看到不同的学习方法。

回答by Jeremy

In my kiosk apps, to make sure no "pressed" characters are lost on a move out of screen-saver (they are usually sent to the PC via a bar code scanner or rfid reader) and to ensure the screen comes back on instantly, I use the following bits of code, along with a transparent cur cursor file, and disable all the screen saving/power saving options in the host OS. This works in Chrome 12, and probably many other browsers. I don't think there is any Chrome-specific code-- it's just the easiest thing to auto-launch into a kiosk-mode.

在我的自助服务终端应用程序中,为了确保在移出屏幕保护程序时不会丢失“按下”字符(它们通常通过条形码扫描仪或 rfid 阅读器发送到 PC)并确保屏幕立即恢复,我使用以下代码位以及透明的光标文件,并禁用主机操作系统中的所有屏幕保存/节能选项。这适用于 Chrome 12,可能还有许多其他浏览器。我认为没有任何特定于 Chrome 的代码——这只是自动启动到信息亭模式的最简单的方法。

The sloppy bits iterating through the INPUT elements are needed because those form parts will keep their default (typically white) background.

需要遍历 INPUT 元素的草率位,因为这些表单部分将保留其默认(通常为白色)背景。

If you use images, or colored text, or other such objects, you'll need to figure out how to deal with those. I'm just building data acquisition apps, so it's just black text up there on the screen. Turning the page background black makes the whole screen black, and prevents burn in.

如果您使用图像、彩色文本或其他此类对象,则需要弄清楚如何处理这些对象。我只是在构建数据采集应用程序,所以它只是屏幕上的黑色文本。将页面背景变黑会使整个屏幕变黑,并防止烧屏。

This could and should be done by applying various CSS bits via JS, but it works, well, and it's all in one spot in the code, so it's easy to paste around, say, to a place like this.

这可以而且应该通过 JS 应用各种 CSS 位来完成,但它可以工作,很好,而且它都在代码中的一个位置,所以很容易粘贴到这样的地方,比如说,到这样的地方。

<body onkeydown="unSS();" id="thePage">

onkeydown fires unSS is in the body so that every time a key press is seen it will reset the timer.

onkeydown 触发 unSS is in body 以便每次看到按键时它都会重置计时器。

<script type="text/javascript">

var ScreenSaver = 10; // minutes

SS(); // start the timer up

function unSS()
{
    document.getElementById('thePage').style.background='White';
    for (var i = 0; i < document.getElementsByTagName('INPUT').length; i++)
        {
            document.getElementsByTagName('INPUT')[i].style.background='White';
        }

    //put the cursor back.
    document.getElementById('thePage').style.cursor = 'default';

    ScreenSaver=10;
}

function SS()
{
    ScreenSaver = ScreenSaver-1;  //decrement. sorry for the vb-style. get over it.

    if (ScreenSaver<=0)
        {
            document.getElementById('thePage').style.background='Black';
            for (var i = 0; i < document.getElementsByTagName('INPUT').length; i++)
                {
                    document.getElementsByTagName('INPUT')[i].style.background='Black';
                }
               //change the cursor to a transparent cursor. 
               //you can find the file on the web. 
               //Search for "transparent cursor cur download"
               document.getElementById('thePage').style.cursor = 'url(transparentCursor.cur)';
        }

    setTimeout("SS();",60000);  // fire the thing again in one minute.
    }
...

回答by Codler

There is a jquery plugin idletimerthat checks if a user is inactive or not.

有一个 jquery 插件idletimer可以检查用户是否处于非活动状态。

回答by Andrew

I have found a simple work-around to intermittent no-cursor problem, is to create a transparent <div id="overlay"> </div>as the last element on the page, and set the css style properties to:

我发现了一个简单的解决间歇性无光标问题的方法,是创建一个透明的<div id="overlay"> </div>作为页面上的最后一个元素,并将 css 样式属性设置为:

#overlay{
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
background-color: transparent;
cursor: none;
margin: 0;
padding: 0;
border: 0;
}

Make the javascript change the visibility to either "visible" or "hidden". A "visible" layer will hide the cursor. Vice-versa with hidden layer.

使 javascript 将可见性更改为“可见”或“隐藏”。“可见”层将隐藏光标。与隐藏层相反。