Giới thiệu
Với sự trợ giúp của các sự kiện như mousedown, mouseup và mousemove, chúng ta có thể dịch chuyển hình ảnh từ đó tạo hiệu ứng kéo thả.
Ví dụ
Ví dụ sau mô tả cách di chuyển hình ảnh bằng jQuery:
<!DOCTYPE html>
<html>
<head>
<style>
#parent{
position: absolute;
margin: 20px;
width: 200px;
height: 200px;
border-radius: 25px;
background-color: khaki;
}
#mover {
position: relative;
margin: 10px;
}
</style>
</head>
<body>
<div id=parent>
<img id="mover" src="https://images.unsplash.com/photo-1613333238609-ef9218f3ddbd?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=100&ixlib=rb1.2.1&q=80&w=100" />
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
let ele = {startPositionX:0,startPositionY:0};
let disp = {x:0,y:0};
$('#parent').on("mousedown",function(e){
let container = $(this);
ele.startPositionX=e.pageX-disp.x;
ele.startPositionY=e.pageY-disp.y;
$(document).on("mousemove",function(e){
disp.x=e.pageX-ele.startPositionX;
disp.y=e.pageY-ele.startPositionY;
$('#mover').css('transform','scale('+1.0+') translate('+disp.x+'px, '+disp.y+'px)');
});
});
$(document).on("mouseup",function(){
$(this).off("mousemove");
});
</script>
</body>
</html>
Kết quả
Đoạn mã trên sẽ cho kết quả sau:

Kéo thả (Drag)
