本地存储:可以将数据存储本地的技术 字符,不安全 cookie: 大小4K,时间,随着http发给服务器 HTML5新增的API:localstorage,sessionStorage 大小5M,时间:永久/会话级,不会随着http发给服务器 localstorage和sessionStorage: 永久/会话 window身上的子对象localstorage console.log(window.localStorage) console.log(localStorage) localStorage对象,使用对象的操作:点,中括号,delete关键字 使用对象操作 localStorage.name = "admin"; localStorage.name = "root"; console.log(localStorage.name) delete localStorage.name; 使用方法操作 localStorage.setItem("name","qwe") localStorage.setItem("a","1") localStorage.setItem("b","2") localStorage.setItem("c","3") localStorage.setItem("b","666") console.log(localStorage.getItem("name")) console.log(localStorage.getItem("a")) console.log(localStorage.getItem("b")) console.log(localStorage.getItem("c")) console.log(localStorage.getItem("d")) localStorage.removeItem("name") localStorage.removeItem("a") localStorage.removeItem("b") localStorage.removeItem("c") localStorage.clear(); //清除所有
利用storage实现同步拖拽
<script> class Move{ constructor(){ this.box=document.querySelector(".box") this.init(); this.getPos(); } getPos(){ this.pos=localStorage.getItem("pos")?JSON.parse(localStorage.getItem("pos")):{}; // this.box.style.left=this.pos.x+"px"; this.box.style.top = this.pos.y + "px"; } init(){ var that=this; this.box.onmousedown=function (eve) { var e1=eve||window.event; console.log(1) document.onmousemove=function (eve) { var e2=eve||window.event that.box.style.left=e2.clientX-e1.offsetX+"px"; that.box.style.top=e2.clientY-e1.offsetY+"px"; var obj={ x:that.box.offsetLeft, y:that.box.offsetTop }; localStorage.setItem("pos",JSON.stringify(obj)); } document.onmouseup = function(){ document.onmousemove = document.onmouseup = null; } }; } } new Move(); </script>
<script> this.box=document.querySelector(".box") this.pos=localStorage.getItem("pos")?JSON.parse(localStorage.getItem("pos")):{}; // this.box.style.left=this.pos.x+"px"; this.box.style.top = this.pos.y + "px"; onstorage=function () { this.pos=localStorage.getItem("pos")?JSON.parse(localStorage.getItem("pos")):{}; // this.box.style.left=this.pos.x+"px"; this.box.style.top = this.pos.y + "px"; } </script>
htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{100px;height:100px;background: red;position: absolute;left:0;top:0;} </style> </head> <body> <div class="box"></div> </body>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{100px;height:100px;background: green;position: absolute;left:0;top:0;} </style> </head> <body> <div class="box"></div> </body>