百度空间 | 百度首页 
 
查看文章
 
js拖拽
2009年02月10日 星期二 22:40
<script type="text/javascript">
//记录当前的拖拽元素
var dragElement = null;
//4个全局变量,用来记录当前拖拽元素以及鼠标的坐标
//由于不可能同时拖拽多个元素,所以不会冲突
var mouseY,mouseX,objY,objX;
//用于动态更新z-index,确保不会造成不该移动的元素瞎动。
var max = 1;
//初始化网页,遍历所有的元素,如果元素的class属性为"drag"
//则对其进行适当地设置
function dragInit(node){
if(node.className == "drag"){
node.onmousedown = down;
document.onmousemove = move;
node.onmouseover = over;
node.style.position = "relative";
node.dragging = false;
}
var children = node.childNodes;
for(var i = 0;i < children.length; i++){
dragInit(children[i]);
}
}
window.onload = function(){
//从document开始遍历
dragInit(document);
//确保在文档的任何位置将鼠标松开都将导致拖拽停止
document.onmouseup = docUp;
window.onblur = docUp;
}
//鼠标按下响应事件
function down(event)
{
event = event || window.event;
//按谁拽谁
dragElement = this;
//记录鼠标的当前坐标
mouseX = parseInt(event.clientX)
+(document.documentElement.scrollLeft || document.body.scrollLeft);
mouseY = parseInt(event.clientY)
+(document.documentElement.scrollTop || document.body.scrollTop);
//记录元素的当前坐标
objY = parseInt(getNodeStyle(dragElement,"top"));
objX = parseInt(getNodeStyle(dragElement,"left"));
//IE不返回未设置的CSS属性
if(!objY)objY=0;
if(!objX)objX=0;
this.style.zIndex = max++;
}
function move(event){
event = event || window.event;
if(dragElement){
var x,y;
//y等于鼠标当前y - 记录的鼠标y + 元素y ,后面的x一样
y = parseInt(event.clientY)
+(document.documentElement.scrollTop || document.body.scrollTop)
- mouseY + objY;
x = parseInt(event.clientX)
+(document.documentElement.scrollLeft || document.body.scrollLeft)
- mouseX + objX;
//更新元素的实际显示
dragElement.style.top = y + "px";
dragElement.style.left = x + "px";
//更新鼠标坐标和元素坐标的记录
objY=y;
objX=x;
mouseX = parseInt(event.clientX)
+(document.documentElement.scrollLeft || document.body.scrollLeft);
mouseY = parseInt(event.clientY)+(
document.documentElement.scrollTop || document.body.scrollTop);
}
}
function docUp(){
//停止拖拽
dragElement = null;
}
function over(){
this.style.cursor = "move";
}
//获得元素的坐标
function getNodeStyle(node,styleName){
var realStyle = null;
if(node.currentStyle){
realStyle = node.currentStyle[styleName];
}else if(window.getComputedStyle){
realStyle = window.getComputedStyle(node,null)[styleName];
}
return realStyle;
}
</script>

类别:Javascript | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu