<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#parent{
width: 600px;
height: 20px;
border: 1px black solid;
position: relative;
margin: auto;
}
#child{
width: 20px;
height: 20px;
background: red;
position: absolute;
top: 0px;
left: 0px;
}
#div{
width: 200px;
height: 200px;
background: goldenrod;
filter:alpha(opacity:0);
opacity: 0.0;
}
</style>
<script>
window.onload = function(){
var parent = document.getElementById(‘parent‘);
var child = document.getElementById(‘child‘);
var mydiv = document.getElementById(‘div‘);
//x,y分别代表鼠标与移动物体的距离(在移动过程中,这个距离始终保持不变)
var x = 0;
var y = 0;
document.onmousedown = function(ev){
var oEvent = ev || event;
x = oEvent.clientX - child.offsetLeft;
document.onmousemove = function(ev){
var oEvent = ev || event;
//m.n分别代表移动物体的横纵坐标
var m = oEvent.clientX - x;
var scale = (child.offsetLeft)/(parent.offsetWidth - child.offsetWidth);
if(m < 0){
m = 0;
}else if(m > (parent.offsetWidth - child.offsetWidth)){
m = parent.offsetWidth - child.offsetWidth;
}
child.style.left = m + ‘px‘;
mydiv.style.filter = ‘alpha(opacity:‘+scale*100+‘)‘;
mydiv.style.opacity = scale;
document.title = scale;
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
return false;
}
}
</script>
</head>
<body>
<div id="parent">
<div id="child"></div>
</div>
<div id="div"></div>
</body>
</html>