今天需要实现一个物块拖动,发现很多方法都无法达到预期效果,现在直接上代码,实现指定块的拖动效果,首先看图中白条距离右边的位置,这是未拖动前,在正中间
这是拖动后,在左上角
上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drag demo</title>
<style>
</style>
</head>
<body>
<div style="background-color: black;width: 500px;height: 500px">
<div style="background-color: white;width: 100px;height: 100px" class="slider"></div>
</div>
<script src="https://cdnjs.cloud/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
$('.slider').mousedown(function(){
$(document).mousemove(function(e){
$('.slider').offset({
left:e.pageX,
top:e.pageY
})
})
$('.slider').mouseup(function(){
$(document).off('mousemove')
})
})
})
</script>
</body>
</html>
OK, 直接放编辑器里预览就能看到效果