Posted in Javascript onJune 28, 2013
相对于上一篇,优化了拖拽的效果。
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>
jquery实现简单的拖拽效果实例兼容所有主流浏览器(优化篇)
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@