Home > Web Front-end > JS Tutorial > Example code for jQuery to realize random dragging of divs (general code)_jquery

Example code for jQuery to realize random dragging of divs (general code)_jquery

WBOY
Release: 2016-05-16 15:17:21
Original
1434 people have browsed it

Pay attention to the location where js is placed. It should be placed close to it. If it is covered by others, it cannot be moved.

For example:

<div id="move">可移动的DIV</div>
Copy after login

Introduce jquery.js, jquery-ui.js,

<script scr="http://code.jquery.com/jquery-1.10.2.js"></script>
<script scr="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Copy after login

One sentence:

$("#move").draggable();
Copy after login

If you wish, the mouse will change into a hand shape when you click and hold:

$("#move").mousedown(function(){
$(this).css("cursor","pointer");
}).mouseup(function(){
$(this).css("cursor","default");
});
Copy after login

Let me share with you a common code jquery to implement a common method of dragging divs

<script type="text/javascript"><!-- 
$(document).ready(function() 
{ 
$(".show").mousedown(function(e)//e鼠标事件 
{ 
$(this).css("cursor","move");//改变鼠标指针的形状 
var offset = $(this).offset();//DIV在页面的位置 
var x = e.pageX - offset.left;//获得鼠标指针离DIV元素左边界的距离 
var y = e.pageY - offset.top;//获得鼠标指针离DIV元素上边界的距离 
$(document).bind("mousemove",function(ev)//绑定鼠标的移动事件,因为光标在DIV元素外面也要有效果,所以要用doucment的事件,而不用DIV元素的事件 
{ 
$(".show").stop();//加上这个之后 
var _x = ev.pageX - x;//获得X轴方向移动的值 
var _y = ev.pageY - y;//获得Y轴方向移动的值 
$(".show").animate({left:_x+"px",top:_y+"px"},10); 
}); 
}); 
$(document).mouseup(function() 
{ 
$(".show").css("cursor","default"); 
$(this).unbind("mousemove"); 
}) 
}) 
// --></script> 
Copy after login

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