前言:实现鼠标拖拽移动div位置,当一次移动完成,鼠标键抬时,此时的位置属性值存入cookie。刷新页面,从新从cookie中取出div的位置属性值,从而实现对div位置的记忆。
1.页面代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box {
position: absolute;
width: 200px;
height: 200px;
border-radius: 15px;
background-color: #E8CCFF;
}
</style>
</head>
<body>
<div class="box"></div>
<script src="cookie.js"></script>
<script>
var box = document.querySelector(".box"); //获取元素
//上来我们先判断是否有位置信息的cookie,
//有的话获取cookie中的div的位置属性值,并将当前div的位置属性值设置为此
if(getCookie("positionDatas")){
let positionDatas = JSON.parse(getCookie("positionDatas"));
positionDatas.forEach((item)=>{
box.style.left = item.left;
box.style.top = item.top;
});
}
var x, y; //鼠标相对与div左边,上边的偏移
var isDrop = false; //移动状态的判断鼠标按下才能移动
box.onmousedown = function(e) {
var e = e || window.event; //要用event这个对象来获取鼠标的位置
x = e.clientX - box.offsetLeft;
y = e.clientY - box.offsetTop;
isDrop = true; //设为true表示可以移动
}
document.onmousemove = function(e) {
//是否为可移动状态
if(isDrop) {
var e = e || window.event;
var moveX = e.clientX - x; //得到距离左边移动距离
var moveY = e.clientY - y; //得到距离上边移动距离
//可移动最大距离
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
//范围限定 当移动的距离最小时取最大 移动的距离最大时取最小
moveX=Math.min(maxX, Math.max(0,moveX));
moveY=Math.min(maxY, Math.max(0,moveY));
box.style.left = moveX + "px";
box.style.top = moveY + "px";
} else {
return;
}
}
//鼠标抬起时,将div的当前位置存储到cookie中去
document.onmouseup = function() {
isDrop = false; //设置为false不可移动
if(getCookie("positionDatas")){
var positionDatas = JSON.parse(getCookie("positionDatas"));
positionDatas.forEach((item) =>{
item.left = box.style.left;
item.top = box.style.top;
})
}else{
var positionDatas = [{left:0,top:0}]
}
//■■■这里用来存入cookie的数据是我们移动后已经改变过位置信息值的positionDatas■■■
setCookie("positionDatas",JSON.stringify(positionDatas),7);
}
</script>
</body>
</html>
2.封装的cookie相关操作API
/**创建cookie
* @param name <string> 要存的cookie名
* @param val <string> 要存的cookie值
* @param n <string> cookie的有效天数
*/
function setCookie(name, val, n) {
let oDate = new Date();
oDate.setDate(oDate.getDate() + n);
document.cookie = name + "=" + escape(val) + ";expires=" + oDate;
}
/**获取cookie 的值
* @param name <string> 要获取的cookie名
*/
function getCookie(name) {
let strCookie = document.cookie;
let arrCookie = strCookie.split("; ");
for (let i = 0; i < arrCookie.length; i++) {
let arr = arrCookie[i].split("=");
if (arr[0] == name) {
return unescape(arr[1]);
}
}
}
/**删除cookie 原理:将当前cookie的有效时间设置为任何过去的时间
* @param name <string> 要删除的cookie名
*/
function removeCookie(name) {
setCookie(name, 1, -1);
}