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

Javascript
在一个form用一个SUBMIT(或button)分别提交到两个处理表单页面的代码
用Javascript读取中文COOKIE的解决办法
功能很全的精品JS计算器
永不消失的title提示代码
一直复略了的一个问题,关于表单重复提交
初探jquery——表单应用范例
懒就要懒到底——鼠标自动点击(含时间判断)
关于表单的两点交互体验改进技巧
javascript知识点收藏
用Javascript做flash做的事..才完成的一个类.Auntion Action var 0.1
如何使页面打开时input就被选中?
点选TOP后并不是直接跳到页顶的,而是滚动上去的
js玩一玩WSH吧
【最新漏洞】IE中使用Rds.DataSpace下载并运行病毒文件
select选择事件问题
SUN的《AJAX与J2EE》全文译了
你真的了解JavaScript吗?
极酷的javascirpt,让你随意编辑任何网页
用javascript编写的第一人称射击游戏
轻轻松松学习JavaScript

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-12   浏览: 540 ::
收藏到网摘: 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>