I'm having a strange error with trying to put a "moving" class on an element when moving/dragging the mouse. I'm using jQuery 3.1.1 on Chrome 59.0.3071.115.
I've simplified my problem down to this example:
<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>
This will display a green box in the page, and fires events when you mouse-down and mouse-up on it.
What happens is...
div
(this can be seen in the Chrome Developer Tools: Elements tab), but the cursor stays the usual arrow. I would expect the cursor to change to the move
cursor. div
-- The cursor switches to the move
cursor for a moment, but switches back to the default arrow if the mouse is moved at all. I've tried solutions like https://stackoverflow.com/a/16172027/1766230 , and others, without luck. I've tried various combinations of selectors in the CSS, various elements, etc. Strangely when attempting this in jsfiddle everything works correct, but with this content as a stand-alone HTML file, I see the error.
Turns out it must have been a browser bug, because when I closed Chrome and re-opened it, this began working as expected. Is anyone aware of this kind of bug in Chrome?
Just an alternative : (without 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>
drag != mousedown
Its a browser default dragging behaviour .Add the drag
event with mousedown
$(document).ready(function() { var $thing = $('.thing'); $thing.on('mousedown ,drag', function(e) { $thing.addClass("moving"); console.log("mousedown"); }).on('mouseup', function(e) { $thing.removeClass("moving"); console.log("mouseup"); }); });
.thing { display: block; width: 10em; height: 10em; background: green; } .moving { cursor: move; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <div class="thing"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.