我在移动/拖动鼠标时试图在元素上放置一个“移动”类时遇到了一个奇怪的错误。我在 Chrome 59.0.3071.115 上使用 jQuery 3.1.1。
我已经将我的问题简化为这个例子:
<html>
<head>
<style>
.thing {
display: block;
width: 10em;
height: 10em;
background: green;
}
.moving {
cursor: move;
}
</style>
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="thing"></div>
<script>
$(document).ready(function(){
var $thing = $('.thing');
$thing.on('mousedown', function(e){
$thing.addClass("moving");
console.log("mousedown");
}).on('mouseup', function(e){
$thing.removeClass("moving");
console.log("mouseup");
});
});
</script>
</body>
</html>
这将在页面中显示一个绿色框,并在您在其上按下和松开鼠标时触发事件。
发生的事情是...
- 单击绿色框——“移动”类被应用于
div
(这可以在 Chrome 开发人员工具中看到:元素选项卡),但光标保持通常的箭头。我希望光标变为move
光标。 - 按住点击的同时,稍微拖动 -- 光标仍保持默认箭头。
- 在绿色
div
上松开鼠标 -- 光标暂时切换到move
光标,但如果移动鼠标则切换回默认箭头完全没有。
我试过类似 https://stackoverflow.com/a/16172027/1766230 的解决方案,和其他人,没有运气。我在 CSS、各种元素等中尝试了各种选择器组合。奇怪的是,在 jsfiddle 中尝试此操作时一切正常,但将此内容作为独立的 HTML 文件时,我看到了错误。
编辑
原来这一定是浏览器错误,因为当我关闭 Chrome 并重新打开它时,它开始按预期工作。有人知道 Chrome 中的这种错误吗?
最佳答案
只是一个替代方案:(没有 JS)
- 使用
tabindex
- 选择器是
:active:hover
.thing {
display: block;
width: 10em;
height: 10em;
background: green;
user-select: none;
outline: none;
}
.thing:active:hover {
cursor: move;
background: red;
}
<div class="thing" tabindex="1"></div>
关于javascript - 移动鼠标时更改光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45094970/