在纯JavaScript中鼠标空闲时强制更新Chrome光标

4
我在以下链接中遇到了类似的问题:https://code.google.com/p/chromium/issues/detail?id=26723。当新的div出现且鼠标不移动时,在Chrome 40中光标不会更新。Chrome的问题列表提供了一些解决方法,但我无法将其应用到我的代码中。也有一些stackoverflow的问题列出了这个问题,但是它们不能使用原始的javascript解决这个特定的情况。
HTML:
<div id ="d">
    Hello
</div>

CSS(层叠样式表):
div#d {
    width: 100px;
    height: 100px;
    background-color: red;
}

div.curs {
    cursor: pointer;
    height: 80px;
    background-color: grey;
}

JS :

setTimeout(function(){
    var div = document.getElementById('d');
    div.innerHTML = div.innerHTML + '<div class="curs">World</div>';    
}, 5000);

这种情况下最简单的原生JavaScript解决方法是什么?

示例代码: http://jsfiddle.net/2zh90st6/

2个回答

3
在Google Chrome v42中,您可以通过更改当前鼠标下的元素或该元素的任何祖先元素的光标样式来安排光标更新。请注意,在将新元素添加到DOM后,必须更改光标样式。

var container, overlay;

container = document.getElementById('container');

setTimeout(function() {
  overlay = document.createElement('div');
  overlay.id = 'overlay';
  container.appendChild(overlay);

  // Change container cursor from 'auto' to 'default',
  // to schedule cursor update while hovering overlay
  container.style.cursor = 'default';
}, 5000);
#container {
  position: relative;
  padding: 10px;
  cursor: auto;
  background: #7FDBFF;
  color: #001F3F;
  width: 100px;
  height: 100px;
}
#overlay {
  cursor: pointer;
  width: 100px;
  height: 100px;
  background: #001F3F;
  color: #7FDBFF;
  position: absolute;
  top: 10px;
  left: 10px;
}
<div id="container">
  Hover me and wait for a dark overlay.
</div>

您提供的链接Issue 26723: 鼠标在闲置时不会更改光标是一个活跃的问题,希望这种解决方法不再需要太长时间。


3
仍然在Chrome 67上遇到这个问题。请注意,如果页面没有键盘焦点(例如按F12并且光标更改),则光标不会更新。其次,如果一个div在静止的鼠标指针下面移动,光标也不会更改。暴力解决方案:http://jsbin.com/qahuqa/1 - 打开并将鼠标指针放在左上角附近:当绿色框移动到鼠标指针下方时,CSS光标将被更新。现在按F12,光标不会更新(因为开发工具有焦点)。从开发工具元素选项卡中,右键单击,删除<div id =“dummyCursorDiv”> </ div>,光标就不会更新了。 - robocat

2

嗯,这很有趣。无论如何,在Chrome v42中触发更改身体的光标似乎是解决问题的方法:

setTimeout(function(){
    var div = document.getElementById('d');
    div.innerHTML = div.innerHTML + '<div class="curs">World</div>';    

    document.body.style.cursor = 'default';

}, 5000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接