效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#wrap{
width: 20px;
height: 500px;
position:absolute;
left: 100px;
top: 100px;
background-color: #ccc;
}
#wrap div{
width: 20px;
height: 50px;
background-color: blue;
position:absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id="wrap">
<div></div>
</div>
<script>
var aDiv = document.querySelectorAll("div");
aDiv[1].onmousedown = function (){
var disY = event.pageY - aDiv[1].offsetTop - aDiv[0].offsetTop; //因为鼠标是相对于页面的定位,而aDiv[1]的offetTop是相对于父元素的定位,所以还要减去父元素相对于自己父元素的定位才能得到
document.onmousemove = function (){
var nTop = event.pageY - disY - aDiv[0].offsetTop;
//子元素div在滚动的过程中不超出父元素的顶部和底部的范围是0-450
nTop = Math.max(nTop,0);
nTop = Math.min(nTop,450);
aDiv[1].style.top = nTop + "px";
}
document.onmouseup = function (){
document.onmouseup = document.onmousemove = null;
}
return false;
}
</script>
</body>
</html>