step1 实现拖拽
- css
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background-color: #ae7000;
cursor: pointer;
text-align: center;
line-height: 200px;
position:absolute;
}
</style>
- html
<body>
<div class="box">drag me</div>
</body>
- js
<script>
let obox = document.querySelector('.box')
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
obox.addEventListener("mousedown",function(event){
// alert(1)
var e = event || window.event
console.log(e);
x = e.clientX; //获取距离窗口最左边的初始距离
y = e.clientY; //获取距离窗口最顶部的初始距离
isDown = true
//获取左部和顶部的偏移量
l = obox.offsetLeft; //目标元素距离父盒子的左边距
t = obox.offsetTop;//目标元素距离父盒子的上边距
//开关打开
isDown = true;
//设置样式
obox.style.cursor = 'move';
})
//鼠标移动
window.onmousemove = function(e) {
if (isDown == false) {
return;
}
//获取x和y
var nx = e.clientX; // 获取距离窗口最左边的初始距离
var ny = e.clientY; //获取距离窗口最顶部的初始距离
//计算移动后的左偏移量和顶部的偏移量
var nl = nx - (x - l); //(x-l) 鼠标在目标元素(div)上的坐标x
var nt = ny - (y - t); //(y-t) 鼠标在目标元素(div)上的坐标x
obox.style.left = nl + 'px';
obox.style.top = nt + 'px';
//step2
//localStorage.setItem('left',nl)
//localStorage.setItem('top',nt)
}
//鼠标抬起事件
obox.onmouseup = function() {
//开关关闭
isDown = false;
obox.style.cursor = 'default';
}
//step2
//if (!isDown && localStorage.getItem('left')) {
//setInterval(()=>{
// let left = localStorage.getItem('left')
// let top = localStorage.getItem('top')
// obox.style.left = left + 'px';
// obox.style.top = top + 'px';
// },17)
//}
</script>
- 图解思路
展示省略
step2 种storage
- 这里主要是 要了解 cookie localStorage session 的区别
cookie:有大小限制4kb左右,最多50条左右,可以设置时长,
会跟随ajax携带在请求头里,存储在客户端 //(磁盘)
localStorage 本地存储,大小限制是5M,除非手动删除,不然一直存在
session 临时存储,会话关闭即消失,存在服务器的内存中,
以上,我们只要不存在session 都可以,巴特,鉴于cookie存取麻烦存在localStorage里
代码把上面step2 打开即可
- 思路
1.每次位置更新都把算好的偏移量,记录下来存到storage
2.当页面没有拖拽事件,并且storage有值,取值更新位置
哈哈,这个场景,2年前面试的时候小白同学我没答上来,纪念下