How can I move elements with the mouse whilst positioning them correct with the cursor?
Like in this fiddle the div always jumps to its 0x0 position:
var isMouseDown = false;
$('div')
.mousedown(function() {
isMouseDown = true;
})
.mouseup(function() {
isMouseDown = false;
})
.mousemove(function(event) {
if(isMouseDown) {
$(this).css({
'top': event.pageY, // Offset missing
'left': event.pageX
});
}
});
Subtract half of the width
of the element to left
and half of the height
of the element to top
.
var isMouseDown = false;
$('div').mousedown(function() {
isMouseDown = true;
}).mouseup(function() {
isMouseDown = false;
}).mousemove(function(event) {
var heightWidth = this.getBoundingClientRect().height/2;
if(isMouseDown) {
$(this).css({'top': event.pageY - heightWidth,'left': event.pageX - heightWidth });
}
});
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.