当前位置: 首页 > 图文教程 > 网络编程 > Javascript > jQuery 可以拖动的div实现代码 修正版

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 jQuery 可以拖动的div实现代码 修正版


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-12   浏览: 614 ::
收藏到网摘: n/a

最近研究了一下jQuery,觉得真的是一个很不错的js库,其他的不说,关键是有翔实的文档,这点是非常关键的。 当然,代码使用起来也非常的方便,很多东西就不用自己再去琢磨了。
研究的过程中顺便用jQuery实现了一个div的拖动,代码附于本文结尾。
实现的思路请参考我的可以拖动的DIV(二)一文。
在参考jQuery中文网站中的例子时,我发现他们在div窗口标题栏触发click事件时,将div的位置移上了一些,而mouseup的事件注册在整个div窗口上,这个思路让我很受启发,解决了鼠标移动很快而div不能跟上导致的错误,非常好的解决办法。
另外,请注意事件起泡,在jQuery以及任何实现div拖动的js代码中,事件起泡无疑都是要阻止的。
在jQuery 的bind或者unbind方法中,函数的返回值最好都用false,不信的话,可以试试true。
这个事件起泡的过程在一般代码中我们用stopPropagation方法来阻止。
效果图:

注意文中加载了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>