JQuery drag div move div pop up layer implementation principle and examples
- 2020-03-30 02:33:25
- OfStack
Code demo:
http://www.imqing.com/demo/movediv.html
General principle:
Make the position of div be absolute, and then control its top and left values. You need to monitor the mouse events, mainly using mousedown, mousemove, mouseup.
After the mousedown, record the location of the div that needs to be moved when the mousedown is mousedown, and then take the difference to get the location of the div after the mousedown is moved. That is:
Left = current mouse position. X - (the value of. X when the mouse is clicked - the x value of the initial position of div)
Top = the current mouse position. Y - (when the mouse is clicked. Y value - the initial position y value of div)
Code:
In fact, the amount of code is not much, hey. The point is that the div position that you need to move is the absolute position, and then detect the mouse event. Hey hey.
http://www.imqing.com/demo/movediv.html
General principle:
Make the position of div be absolute, and then control its top and left values. You need to monitor the mouse events, mainly using mousedown, mousemove, mouseup.
After the mousedown, record the location of the div that needs to be moved when the mousedown is mousedown, and then take the difference to get the location of the div after the mousedown is moved. That is:
Left = current mouse position. X - (the value of. X when the mouse is clicked - the x value of the initial position of div)
Top = the current mouse position. Y - (when the mouse is clicked. Y value - the initial position y value of div)
Code:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Qing's Web</title>
<script src="./jquery-1.7.2.min.js" type="text/javascript"></script>
<style type="text/css">
.footer {
position: fixed;
bottom: 0;
width: 100%;
}
.moveBar {
position: absolute;
width: 250px;
height: 300px;
background: #666;
border: solid 1px #000;
}
#banner {
background: #52CCCC;
cursor: move;
}
</style>
</head>
<body style="padding-top: 50px;">
<div class="moveBar">
<div id="banner"> Press and hold to move current div</div>
<div class="content"> Here's something else </div>
</div>
<div class="footer">
<p align="center" class="label">ALL Rights Reserved Qing All rights reserved </p>
</div>
<script>
jQuery(document).ready(
function () {
$('#banner').mousedown(
function (event) {
var isMove = true;
var abs_x = event.pageX - $('div.moveBar').offset().left;
var abs_y = event.pageY - $('div.moveBar').offset().top;
$(document).mousemove(function (event) {
if (isMove) {
var obj = $('div.moveBar');
obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});
}
}
).mouseup(
function () {
isMove = false;
}
);
}
);
}
);
</script>
</body>
</html>
In fact, the amount of code is not much, hey. The point is that the div position that you need to move is the absolute position, and then detect the mouse event. Hey hey.