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

Javascript
javascript的事件描述
用javascript动态注释掉HTML代码
对联广告
[原创]菜单制作学习一个小东西
JavaScript中的私有成员
基于Web标准的UI组件 — 树状菜单(2)
JavaScript静态的动态
JavaScript Base64编码和解码,实现URL参数传递。
跨浏览器的设置innerHTML方法
多个iframe自动调整大小的问题
判断checkbox选择的个数 多浏览器
发现的以前不知道的函数
Js+XML 操作
Javascript里使用Dom操作Xml
JS+CSS模拟IP输入框
prototype1.5 初体验
prototype 源码中文说明之 prototype.js
prototype1.4中文手册
获取页面高度,窗口高度,滚动条高度等参数值getPageSize,getPageScroll
js实现ASP分页函数 HTML分页函数

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


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