js拖拽的封装

原创 Richaren 随笔 待整理 787阅读 2014-08-20 08:51:21 举报

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">;
<html xmlns="http://www.w3.org/1999/xhtml">;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<ul style="width:100px;height:100px;background:#0F0;position:absolute"></ul>
<div style="width:100px;height:100px;background:#ccc;position:absolute"></div>
</body>
<script>
drag('ul');
drag('div');
function drag(obj){
var object=document.getElementsByTagName(obj)[0];
object.onmousedown=function(event){
var x=event.clientX;
var y=event.clientY;

    var disx=x-object.offsetLeft;
    var disy=y-object.offsetTop;    
    document.onmousemove=function(event){
        object.style.left=event.clientX-disx+"px";
        object.style.top=event.clientY-disy+"px"; 

    }   
    document.onmouseup=function(){
        document.onmousemove=null;
        document.onmouseup=null;
    }
    return false//阻止默认行为
}

}
</script>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复