jquery實現簡單的拖拽效果執行個體相容所有主流瀏覽器(最佳化篇)

來源:互聯網
上載者:User

相對於上一篇,最佳化了拖拽的效果。
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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.