基本上msn、microsoft live 和google个性主页 元素可拖动并放置的的实现原理就是对dom的操作再加上javascript拖动元素。实现起来实际上并不难,但是要做到很美观并符合用户习惯就需要一些时间思考了。
以下代码实现了上述功能,虽然很简单,但是基本上说明了原理。实现更高级的功能当然还需要改进。
<!doctype html public “-//w3c//dtd html 4.0 transitional//en” >
<html>
<head>
<title>droplayer2</title>
<meta name=”generator” content=”microsoft visual studio .net 7.1″>
<meta name=”code_language” content=”c#”>
<meta name=”vs_defaultclientscript” content=”javascript”>
<meta name=”vs_targetschema” content=”http://schemas.microsoft.com/intellisense/ie5″>
<style type=”text/css”>
div
{
border-right: lightgrey thin solid;
border-top: lightgrey thin solid;
font-weight: bold;
z-index: 2;
text-transform: capitalize;
border-left: lightgrey thin solid;
color: white;
border-bottom: lightgrey thin solid;
background-color: dimgray;
}
</style>
</head>
<body>
<div id=”parentdiv” class=”parentcss” style=”width:100″>
<div class=”itemcss” onmouseover=”insertdiv(this)”>one 1</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>two 2</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>three 3</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>four 4</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>five 5</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>six 6</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>seven 7</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>eight 8</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>nine 9</div>
<div class=”itemcss” onmouseover=”insertdiv(this)”>ten 10</div>
</div>
<script language=”javascript”>
<!–
var obj,obj2; //引发事件对象
var rootnode; //控制对象根节点
var isdrag=false; //是否抓起
var nulldiv; //空临时层
var x,y; //鼠标与控件的相对坐标
window.onload = prepare; //窗体加载时委托到prepare
function prepare()
{
//生成临时层,并设置其属性
nulldiv = document.createelement(“div”);
//获得控制对象的根节点元素
rootnode = document.getelementbyid(“parentdiv”);
document.onmousemove=moveit; //当鼠标在文档上移动时事件委托到moveit
document.onmousedown=drag; //当鼠标按下时事件委托到drag
document.onmouseup=release; //当鼠标释放台起时事件委托到release
}
function drag()
{
obj = event.srcelement;
x=0;//event.offsetx;
y=0;//event.offsety;
obj.style.position=absolute;
obj.style.postop=event.y-y;
obj.style.posleft=event.x-x;
isdrag=true;
}
function moveit()
{
//window.status = event.x+”|”+event.y+”|”+isdrag+”|”+x+”|”+y;
if(isdrag)
{
obj.style.postop=event.y-y;
obj.style.posleft=event.x-x;
}
}
function release()
{
isdrag=false;
nulldiv.style.display=none;
obj.style.position=;
rootnode.insertbefore(obj,obj2);
}
function insertdiv(o)
{
if(isdrag)
{
obj2=o;
nulldiv.style.display=;
nulldiv.style.height=18;
nulldiv.style.width=100;
rootnode.insertbefore(nulldiv,obj2);
}
}
//–>
</script>
</body>
</html>