鼠标按下时CSS光标更改不起作用

Posted

技术标签:

【中文标题】鼠标按下时CSS光标更改不起作用【英文标题】:CSS cursor change not working when mouse is down 【发布时间】:2013-03-18 13:56:01 【问题描述】:

我将鼠标放在更改光标的 html 元素上。现在,如果用户在仍然按下鼠标按钮的同时按下一个键,我将另一个光标分配给该元素。这在 Mozilla 上运行得非常好,它会立即更改光标,但不能在 chrome 中。在 chrome 中,我需要将光标移动至少一个像素才能使新光标可见。请注意,这仅在按下鼠标按钮时发生。如果没有,光标会根据需要立即切换。知道如何正确解决这个问题吗?

更新:我刚刚发现这似乎是 WebKit 中的一个错误: https://bugs.webkit.org/show_bug.cgi?id=53341

但无论如何,由于还没有解决办法,有什么办法让它仍然有效吗?

以下是错误行为的示例:JSFiddle Sample,代码如下:

html:

<div id="test1" style="background:blue;width:200px;height:200px;color:white">Case #1 -   cursor not changing for mousedown before moving it (Press mouse - nothing happens. Then hold mouse and move)</div>

<div id="test2" style="background:red;width:200px;height:200px;color:white">Case #2 - cursor not changing for mousedown before moving it when pressing a key (Press mouse, then click any key - Nothing happens. Then hold mouse and move)</div>

js:

var el1 = document.getElementById("test1");
var el2 = document.getElementById("test2");

el1.addEventListener("mousedown", function() 
    el1.style.cursor = "move";
);

document.addEventListener("keydown", function() 
    el2.style.cursor = "move";
);

【问题讨论】:

想制作小提琴吗? 向我们展示您的代码 HTML/JS/CSS 您是否尝试过通过使用 javascript 添加删除类来做到这一点?另外..你为什么使用内联样式?问候, 是的,我实际上是在使用 JS 添加/删除类,但确实在这里添加了一个更简单的内联样式示例。两者都产生相同的效果。 我刚刚测试了您的代码,它对我有用,无需移动光标。 (铬) 【参考方案1】:

这在 chrome 中对我有用,无需移动鼠标:

var el1 = document.getElementById("test1");
var el2 = document.getElementById("test2");

el1.addEventListener("mousedown", function() 
    el1.className += ' cursormove';  
);
document.addEventListener("keydown", function() 
    el1.style.cursor = "pointer";
);


.cursormove cursor:move;

http://jsfiddle.net/ntdap5hf/4/

还是我错过了什么?

【讨论】:

是的,它可以在 Chrome 下的 jsfiddle 中运行!但是在没有 jsfiddle 的 Chrome 下 - 有时是的,有时不是 :(( 在我的 Chrome-66.0.3359.139 中可能会发生什么?

以上是关于鼠标按下时CSS光标更改不起作用的主要内容,如果未能解决你的问题,请参考以下文章

鼠标左键按下时如何更改鼠标光标?

按下时如何更改 IconButton 的图标

WPF DataGridCheckBoxColumn检查/取消选中有时不起作用

当孩子是芯片小部件时,Flutter MouseRegion 不起作用

如果在表格单元格中,CSS悬停更改其他文本/类的样式不起作用

Java:将鼠标光标下当前像素的颜色打印到控制台:鼠标侦听器不起作用