[英]Moving element with Javascript with correct cursor positioning
如何在用光標正確定位元素的同時用鼠標移動元素?
像這個小提琴一樣,div總是跳到其0x0位置:
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
});
}
});
將元素width
的一半減到left
,將元素height
的一半height
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 });
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.