我正在处理拖放代码中的问题。代码实际上有效,但我想做两件事:
使动作更平滑。我正在寻找的效果类似于这个插件http://draggabilly.desandro.com/(参见第一个例子)。如果你比较下面的代码和这个代码,你可以看到第二个代码的平滑程度,(特别是如果你更快地移动它)。
修复拖动动作错误。在我的代码中,当您更快地移动div时,有时div会停止移动,并且只有当鼠标的光标再次进入时才会恢复其移动。我尝试使用此代码解决它,但它不能像我想的那样工作。
if (mouseX < offset.left && mouseX > offset.left + $('.movable').width()){
$('.movable').css("left", mouseX);
}
if (mouseY < offset.top && mouseY > offset.top + $('.movable').height()){
$('.movable').css("top", mouseY);
}
这是我的代码的小提琴:
function endMove() {
$(this).removeClass('movable');
}
function startMove() {
var offset = $('.movable').offset();
var mouseX = event.pageX;
var mouseY = event.pageY;
var posX = mouseX - offset.left;
var posY = mouseY - offset.top;
$('.movable').on('mousemove', function(event) {
var thisX = event.pageX - posX,
thisY = event.pageY - posY;
$('.movable').offset({
left: thisX,
top: thisY
});
if(mouseX < offset.left && mouseX > offset.left + $('.movable').width()){
$('.movable').css("left", mouseX);
}
if(mouseY < offset.top && mouseY > offset.top + $('.movable').height()){
$('.movable').css("top", mouseY);
}
event.preventDefault();
});
}
$(document).ready(function() {
$("#containerDiv").on('mousedown', function() {
$(this).addClass('movable');
startMove();
}).on('mouseup', function() {
$(this).removeClass('movable');
endMove();
});
});
#containerDiv {
background:#333;
position:absolute;
width:200px;
height:100px;
cursor:move ;
line-height:100px;
text-align:center;
color:#fff;
border:#aaa 1px solid;
}
#containerDiv.movable {
background:#ef0;
color:#444;
border:#000 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="containerDiv"></div>
我想使用jQuery(没有UI,没有插件)做这两件事,是否可能?提前致谢。
答案 0 :(得分:0)
希望这会有所帮助
var TheDraggable = null;
$(document).ready(function() {
$('.draggable').on({
mousedown: function() {
console.log('mousedown');
TheDraggable = $(this);
$('html').addClass('cursormove');
},
mouseup: function() {
console.log('mouseup');
TheDraggable = null;
//console.log('mouseup');
$('html').removeClass('cursormove');
}
});
$(document).mousemove(function(e) {
if (TheDraggable) {
var TheLeft = e.pageX;
var TheTop = e.pageY;
TheDraggable.css({
'top': TheTop,
'left': TheLeft
});
}
});
});
&#13;
.draggable {
position: absolute;
height: 100px;
width: 100px;
background-color: #eee;
border: 1px solid black;
cursor: move;
}
.cursormove:hover {
cursor: move;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="draggable">Drag me</div>
&#13;