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:
Qing's Web
< ;body style="padding-top: 50px;">
Click here to move the current div< ;/div>
Here is other content
<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.
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