|
<!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>JavaScript拖拽示例网页——解决快速拖拽的问题</title>
<meta name="Description" content="JavaScript拖拽文章的配套示例网页。本例解决了快速拖拽的时候元素停止移动的问题。" />
<meta name="Keywords" content="拖拽,实例,DOM,JavaScript,JScript" />
<style type="text/css">
.drag{border:1px solid; width:400px; background:#CCCCCC;}
#test1{ top:20px;}
#test2{ left:40px;}
</style>
<script type="text/javascript">
var dragElement = null;
var mouseY;
var mouseX;
var x="";
var y="";
var max = 1;
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);
}
}
window.onload = function(){
dragInit(document);
document.onmouseup = docUp;
}
function down(event)
{
event = event || window.event;
dragElement = this;
mouseX = parseInt(event.clientX);
mouseY = parseInt(event.clientY);
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 = event.clientY - mouseY + objY;
x = event.clientX - mouseX + objX;
dragElement.style.top = y + "px";
dragElement.style.left = x + "px";
//移动完元素之后,延迟一段时间
document.onmousemove = null;
setTimeout("document.onmousemove = move;",40);
}
}
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>
</head>
<body>
<div class="drag" id="test1">
<p>我是拖拽示例DIV1。</p>
<p>可以试验一下效果。</p>
</div>
<div class="drag" id="test2">
<p>我是拖拽示例DIV2。</p>
</div>
</body>
</html>
|
|