JS实现:标题栏拖拽移动案例

实现内容

  1. 只能按在标题栏拖拽,此处运用事件委托
  2. 点击返回按钮,可以返回初始盒子初始位置, 利用数组对象,记录盒子移动的距离信息,最后运用间隙性定时器完成。
  3. 设置边界,不能超出浏览器可视窗口,运用 (页面的可是宽度 - 对象的宽度) 同理高度
  4. 效果图

JS实现:标题栏拖拽移动案例_间歇性定时器


  1. 代码
<!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>标题栏拖拽</title>
<style>
#box{
width: 400px;
height: 200px;
border: 1px solid #000;
position: absolute;
left: 0;
top: 0;
}
#title{
width: 100%;
height: 30px;
border: 1px solid rgb(96, 224, 139);
position: absolute;
left: 0;
top: 0;
}
#ret{
/* float: right; */
height: 100%;
position: absolute;
right: 0;
top: 0;
}

</style>
</head>
<body>
<div id="box">
<div id="title">
<input type="button" name="" id="ret" value="返回">
</div>
</div>

<script>
var oTitle = document.getElementById("title");
var oDiv = document.getElementById("box");
var oBtn = document.getElementById("ret");
var html = document.documentElement;

// 记录盒子 位置信息
var arr = [];
// 定时器
var timer = null;
oDiv.onmousedown = function(evt){
var e = evt || window.event;
//事件源
var target = e.target || e.srcElement
if(target.id === "title"){
var disX = e.offsetX; // 获取当前对象距离鼠标的位置
var disY = e.offsetY;
// 记录盒子初始位置
arr.push({left:oDiv.offsetLeft, top:oDiv.offsetTop}); //offsetLeft 获取相对于父元素的距离
// 鼠标移动
document.onmousemove = function(evt){
// 这里也必须写上事件对象
var e = evt || window.event
var left = e.pageX - disX;
var top = e.pageY - disY;
// 限制界限
if(left <= 0){
left = 0;
}else if(left >= html.clientWidth - oDiv.clientWidth){
left = html.clientWidth - oDiv.clientWidth;
}
if(top <= 0){
top = 0;
}else if(top >= html.clientHeight - oDiv.clientHeight){
top = html.clientHeight - oDiv.clientHeight;
}
oDiv.style.left = left + 'px';
oDiv.style.top = top + 'px';

arr.push({left:oDiv.offsetLeft, top:oDiv.offsetTop}); // 盒子移动的距离都记录在数组中
}
// 取消鼠标移动
document.onmouseup = function(){
document.onmousemove = null;
}
// 回到初始位置
oBtn.onclick = function(){
// 一键返回
// oDiv.style.left = 0;
// oDiv.style.top = 0;

// 动态式返回
clearInterval(timer); // 最好无论有无 在前面加一个
var index = arr.length - 1;
// 间隙定时器
timer = setInterval(function(){
oDiv.style.left = arr[index].left + 'px';
oDiv.style.top = arr[index --].top + 'px';

if(index == -1){
clearInterval(timer);
// 不清除 之前移动过的盒子的移动轨迹会存留 下一次返回的时候 会把之前的都移动一遍
// 所以 每次返回后要清空arr
arr = [];
}
}, 50)

}
}
}

</script>
</body>
</html>