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

Javascript
一个js写的日历(代码部分网摘)
IE,firefox(火狐)浏览器无提示关闭窗口js实现代码小结
jquery 子窗口操作父窗口的代码
用JavaScript隐藏控件的方法
js 冒泡事件与事件监听使用分析
ie与ff下的event事件
比较全面的event对像在IE与FF中的区别 推荐
js 获取中文拼音,Select自动匹配字母获取值的代码
JavaScript 变量命名规则
没有form表单情况下敲回车键提交表单的js代码
jQuery 使用手册(四)
jQuery 使用手册(六)
jQuery 使用手册(七)
Javascript 数组添加一个 indexOf 方法的实现代码
Javascript 数组添加 shuffle 方法的实现代码
Javascript 两个窗体之间传值实现代码
Javascript showModalDialog两个窗体之间传值
js 覆盖和重载 函数
JavaScript中Object和Function的关系小结
javascript parseInt 大改造

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


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