<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
width: 200px;
height: 1200px;
background-color: #fff;
border: 1px solid skyblue;
position: relative;
}
.box {
width: 200px;
height: 200px;
background-color: pink;
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="container"></div>
<script>
var box = document.querySelector('.box');
// 鼠标一移动就会触发事件
box.addEventListener('mousedown', function(e) {
// 获取鼠标点击时在盒子内的位置
let x = e.pageX - this.offsetLeft;
let y = e.pageY - this.offsetTop;
console.log("object", e, this.offsetLeft, this.offsetTop);
// 添加点击事件
document.addEventListener('mousemove', move)
function move(e) {
// 实时修改盒子的位置
box.style.left = e.pageX - x + 'px'
box.style.top = e.pageY - y + 'px'
}
// 鼠标弹起时清除鼠标移动事件
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move)
})
})
var timer = null;
box.addEventListener('click', function(){
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn(){
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if(oTop > 0){
scrollTo(0,oTop-50);
timer = requestAnimationFrame(fn);
}else{
cancelAnimationFrame(timer);
}
});
})
</script>
</body>
</html>