我創建了一個簡單的可拖動 div 并且它的作業有點好,但是當我嘗試拖動它時,滑鼠游標在跳躍,這里有什么問題?
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(document.body).on("mousedown", ".titleDraggble", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
.titleDraggble {
width: 40px;
height: 40px;
position: absolute;
left: 20px;
top: 20px;
border: 1px solid #000;
cursor: move;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titleDraggble"></div>
uj5u.com熱心網友回復:
- 您需要定義主體高度/寬度才能檢測整個頁面上的事件。如果不這樣做,
body它只是角落某個地方的一個小元素。 - 單擊元素后,不要將其移動到
e.pageY and e.pageX而是使用元素尺寸進行計算。
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY - $dragging.width() / 2,
left: e.pageX - $dragging.height() / 2,
});
}
});
$(document.body).on("mousedown", ".titleDraggble", function(e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function(e) {
$dragging = null;
});
.titleDraggble {
width: 40px;
height: 40px;
position: absolute;
left: 20px;
top: 20px;
border: 1px solid #000;
cursor: move;
}
body {
width: 100%;
height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titleDraggble"></div>
uj5u.com熱心網友回復:
如果包含 jqueryUI,則可以使用可拖動功能:
$('.titleDraggble').draggable()
https://jsfiddle.net/jdpzL6yx/
uj5u.com熱心網友回復:
如果要防止滑鼠游標跳躍,則必須考慮滑鼠相對于目標元素的偏移量。
var $dragging = null;
var offsetx = null;
var offsety = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY - offsety,
left: e.pageX - offsetx
});
}
});
$(document.body).on("mousedown", ".titleDraggble", function (e) {
var rect = e.target.getBoundingClientRect();
offsetx = e.clientX - rect.left;
offsety = e.clientY - rect.top;
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
.titleDraggble {
width: 40px;
height: 40px;
position: absolute;
left: 20px;
top: 20px;
border: 1px solid #000;
cursor: move;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titleDraggble"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324889.html
標籤:javascript html 查询 css
上一篇:Div應該只固定在其他div內
下一篇:單擊跨度元素時,模態不會關閉
