Home > Web Front-end > JS Tutorial > jQuery dragging div, moving div, and pop-up layer implementation principles and examples_jquery

jQuery dragging div, moving div, and pop-up layer implementation principles and examples_jquery

WBOY
Release: 2016-05-16 16:53:02
Original
1247 people have browsed it

Code demonstration:

http://www.imqing.com/demo/movediv.html

General principle:

Make the position of the div absolute, and then control Its top and left values ​​need to monitor mouse events, mainly mousedown, mousemove, and mouseup.

After mousedown, record the position of the mouse and the div that needs to be moved during mousedown, and then get the difference between the two to get the position of the div after the mouse moves. That is:

left = current mouse position.x - (.x value when the mouse is clicked - x value of the initial position of the div)
top = current mouse position.y - (.y when the mouse is clicked value - the initial position y value of the div)

Code:

Copy code The code is as follows:





Qing's Web



< ;body style="padding-top: 50px;">




<script> <br>jQuery(document).ready ( <br>function () { <br>$('#banner').mousedown( <br>function (event) { <br>var isMove = true; <br>var abs_x = event.pageX - $(' div.moveBar').offset().left; <br>var abs_y = event.pageY - $('div.moveBar').offset().top; <br>$(document).mousemove(function (event ) { <br>if (isMove) { <br>var obj = $('div.moveBar'); <br>obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y}); <br>} <br>} <br>).mouseup( <br>function () { <br>isMove = false; <br>} <br>); <br>} <br> ); <br>} <br>); <br></script>



Actually, there is not much code Yes, hehe. The key point is that the position of the div that needs to be moved is absolutely positioned, and then the mouse event is detected. hey-hey.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template