<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script>...
var ms=0;
var src=0;
var srcWidth=0;
var srcHeight=0;
var len="10px";
function did(obj,targ)...{
ms=obj;
src=targ;
document.getElementById(src).style.backgroundColor="#e0e0e0";
document.getElementById(src).style.width= "250px";
document.getElementById(src).style.height= "80px";
event.srcElement.setCapture();
x=document.all(ms).style.pixelLeft-event.x;
y=document.all(ms).style.pixelTop-event.y;
} 

function document.onmousemove()...{ 
if(ms)...{
document.getElementById(ms).style.pixelLeft=x+event.x;
document.getElementById(ms).style.pixelLeft=x+event.x;
document.getElementById(ms).style.pixelTop=y+event.y;
}
} 

function document.onmouseup()...{ 
if(ms)...{
document.getElementById(src).style.backgroundColor="#f2f2f2";
document.getElementById(src).style.width= "300px";
document.getElementById(src).style.height= "100px";
event.srcElement.releaseCapture();
ms=0;
}
}
</script> 
<body>
<div id="a1" style="position:absolute; ">
<div id="a2" onmousedown="did('a1','a2')" style="background-color: #f2f2f2; height:100px; width:300px; cursor: move;">拖动层</div>
</div>
</body>
本文介绍了一种使用JavaScript实现元素拖动效果的方法。通过监听鼠标事件并利用HTML元素的样式属性来改变元素的位置,实现了元素在网页上的自由拖动。文章提供了完整的代码示例,包括如何设置初始样式、捕获鼠标点击事件、处理鼠标移动和释放等关键步骤。
1339

被折叠的 条评论
为什么被折叠?



