jQuery 可以拖动的div实现代码 脚本之家修正版

  当然,代码使用起来也非常的方便,很多东西就不用自己再去琢磨了。

  研究的过程中顺便用jQuery实现了一个div的拖动,代码附于本文结尾。

  实现的思路请参考我的可以拖动的DIV(二)一文。

  在参考jQuery中文网站中的例子时,我发现他们在div窗口标题栏触发click事件时,将div的位置移上了一些,而mouseup的事件注册在整个div窗口上,这个思路让我很受启发,解决了鼠标移动很快而div不能跟上导致的错误,非常好的解决办法。

  另外,请注意事件起泡,在jQuery以及任何实现div拖动的js代码中,事件起泡无疑都是要阻止的。

  在jQuery 的bind或者unbind方法中,函数的返回值最好都用false,不信的话,可以试试true。

  这个事件起泡的过程在一般代码中我们用stopPropagation方法来阻止。

  效果图:

jQuery 可以拖动的div实现代码 脚本之家修正版

  注意文中加载了jquery-1.2.6.js

  

复制代码 代码如下:

  <script language="javascript" type="text/javascript" src="jquery-1.2.6.js"></script>

  <style type="text/css">

  <!–

  body {

  background-color: #333333;

  }

  .win{

  position:absolute;

  top:0px;

  left:0px;

  width:300px;

  height:222px;

  }

  .title{

  height:20px;

  width:300px;

  position:absolute;

  background-color:#666666;

  float:inherit;

  top:0px;

  left:0px;

  background-image:url(bgo.gif);

  }

  .winCon{

  height:200px;

  width:298px;

  position:absolute;

  border:solid;

  border-width:1px;

  border-color:#666666;

  border-top:none;

  float:inherit;

  left:0px;

  top:20px;

  }

  –>

  </style>

  <a href="#" onclick="addDiv(this,'asd');">asgfsdg</a>

  <a href="#" id="zxca" onclick="addDiv(this,'zxc');">asgfsdg</a>

  <script language="javascript" type="text/javascript">

  function addDiv(element,str){

  $(document.body).append("<div class='win' id='win"+str+"‘><div class='title' id='"+str+"‘></div><div class='winCon'>asfsdgfsdgsd</div></div>");

  $("#"+str).mousedown(function(event){

  var offset = $(this).offset();

  _x=event.clientX-offset.left;

  _y=event.clientY+20-offset.top;

  $("#win"+str).css({"top":offset.top-20+"px"});

  $("#win"+str).mousemove(function(event){

  _xx=event.clientX-_x;

  _yy=event.clientY-_y;

  this.style.left=_xx+"px";

  this.style.top=_yy+"px";

  this.style.zIndex="100″;

  return false;

  });

  return false;

  });

  $("#win"+str).mouseup(function(){

  $(this).unbind("mousemove");

  $(this).css({"z-index":"-1″});

  return false;

  });

  element.removeEventListener("click",true);

  }

  </script>