<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#parent {width:600px; height:20px; background:#CCC; position:relative; margin:10px auto;}
#div1 {width:20px; height:20px; background:red; position:absolute; left:0; top:0;}
</style>
<script>
window.onload=function ()
{
var oDiv=document.getElementById('div1');
var oParent=document.getElementById('parent');
var disX=0;
oDiv.onmousedown=function (ev)
{
var oEvent=ev||event;
disX=oEvent.clientX-oDiv.offsetLeft;
document.onmousemove=function (ev)
{
var oEvent=ev||event;
var l=oEvent.clientX-disX;
if(l<0)
{
l=0;
}
else if(l>oParent.offsetWidth-oDiv.offsetWidth)
{
l=oParent.offsetWidth-oDiv.offsetWidth;
}
oDiv.style.left=l+'px';
};
document.onmouseup=function ()
{
document.onmousemove=null;
document.onmouseup=null;
};
return false; //chrome、ff、IE9
};
};
</script>
</head>
<body>
<div id="parent">
<div id="div1"></div>
</div>
</body>
</html>
舞歌
相关分类