4

我想按住鼠标并将其光标更改为图像。然后,当我释放鼠标时,我希望它恢复到默认值。

这是我到目前为止的代码。除非您右键单击然后单击鼠标左键,否则它不起作用。诡异的。

http://jsfiddle.net/HLLNN/

查询

$("#background").on("mousedown", function () {
    $(this).addClass("mouseDown");
}).on("mouseup", function () {
    $(this).removeClass("mouseDown");
});

CSS

.mouseDown{
 cursor:progress  ; // I will eventually want an image file but I used this for brevity

}


#background{
    width:500px;
    height:500px;
    position:absolute;
    background-color:red;
}
4

3 回答 3

8

Well there is 2 things.

First, you have to prevent default. The default behavior is the drag (text selection) wich override your cursor.

$("#background").on("mousedown", function (e) {
    e.preventDefault();
    $(this).addClass("mouseDown");
}).on("mouseup", function () {
    $(this).removeClass("mouseDown");
});

Second, while your mouse is down, you need to move the cursor else it doesnt work. I don't know why and didnt find a fix yet.

Anyway, check this fiddle : http://jsfiddle.net/HLLNN/3/

于 2013-06-14T20:52:27.050 回答
2

似乎有时会出现奇怪的情况,Crome 在mousedown之后没有正确更改光标。我也有光标在mouseup事件后不久发生变化的情况:(

但是https://jsfiddle.net/romleon/429rf1tb/中的纯示例 可以正常工作

var moved=document.getElementsByClassName('moved')[0]
moved.onmousedown = function(){
  moved.classList.add('do_move')
}
 moved.onmouseup = function(){
  moved.classList.remove('do_move')
}
.moved{  
    position: absolute;
    width:111px;
    height:55px;
    background-color: blue;
}
.moved:hover {cursor: pointer;}
.moved.do_move:hover {cursor: crosshair;}
<div class='moved'>
</div>

于 2017-08-16T09:22:44.820 回答
1

return false;在末尾添加 amousedown也有帮助。

$("#background").on({
  "mousedown": function (e) {
    $(this).addClass("mouseDown");
    return false; //added this
  },
  "mouseup": function () {
    $(this).removeClass("mouseDown");
  }
});
于 2013-06-14T21:02:10.587 回答