相對於上一篇,優化了拖拽的效果。
js代碼:fun.js
. 代碼如下:
_MoveObj = null;//全部變量,用來表示當前div
z_index = 0;//z方向
jQuery.fn.myDrag=function(){
_IsMove = 0; //是否移動 1.移動
_MouseLeft = 0; //div left坐標
_MouseTop = 0; //div top坐標
$(document).bind("mousemove",function(e){
if(_IsMove==1){
$(_MoveObj).offset({top:e.pageY-_MouseLeft,left:e.pageX-_MouseTop});
}
}).bind("mouseup",function(){
_IsMove=0;
$(_MoveObj).removeClass("downMouse");
});
return $(this).bind("mousedown",function(e){
_IsMove=1;
_MoveObj = this;
var offset =$(this).offset();
_MouseLeft = e.pageX - offset.left;
_MouseTop = e.pageY - offset.top;
z_index++;
_MoveObj.style.zIndex=z_index;
$(_MoveObj).addClass("downMouse");
});
}
html代碼:
. 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>demo.htm</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="myFun.js" type="text/javascript"></script>
<style type="text/css">
.myDiv{
background:#EAEAEA;
width: 100px;
height: 100px;
border: 1px solid;
cursor: pointer;
text-align: center;
line-height: 100px;
}
.downMouse{
cursor:move;
filter:alpha(Opacity=80);
-moz-opacity:0.5;
opacity: 0.5;
background-color:#ffffff;
}
</style>
<script type="text/javascript">
$(function(){
$(".myDiv").myDrag();
//$("#myDiv2").myDrag();
})
</script>
</head>
<body>
<div id="myDiv1" class="myDiv">拖拽1</div>
<div id="myDiv2" class="myDiv">拖拽2</div>
<div id="myDiv3" class="myDiv">拖拽3</div>
<div id="myDiv4" class="myDiv">拖拽4</div>
<div id="myDiv5" class="myDiv">拖拽5</div>
<div id="myDiv6" class="myDiv">拖拽6</div>
<div id="show"></div>
</body>
</html>