storage事件的拖拽应用

mac2026-06-11  15

实现在两个页面中的方块拖拽其中一块另一个方块的移动 一个方块移动产生的实时的定位值放到本地存储中,另一个方块获取本地存储的值,作为自己的定位 html1中:

<div class="box"></div> <script> var obox=document.querySelector(".box"); //初始值 红色的最后存的位置 var pos=JSON.parse(localStorage.getItem("qwe")); obox.style.left=pos.x+"px"; obox.style.top=pos.y+"px"; //localStorage发生改变触发 读取其中的localStorage发生改变 onstorage=function(eve){ var pos=JSON.parse(eve.newValue); // console.log(pos);//对象 x,y obox.style.left=pos.x+"px"; obox.style.top=pos.y+"px"; } // 每次运动的时候,存取位置 跟随着一起运动 class Drag{ constructor() {

this.ele=document.querySelector(".box"); this.init(); } init(){ //初始读取位置 var p=JSON.parse(localStorage.getItem(“qwe”)); this.ele.style.left=p.x+“px”; this.ele.style.top=p.y+“px”;

var that=this; this.ele.onmousedown=function(eve){ // var e=eve || window.event; that.x=eve.offsetX; that.y=eve.offsetY; that.down(); } } down(){ var that=this;

document.οnmοusemοve=function(eve){ that.move(eve); } document.οnmοuseup=function(){ that.up(); } } move(e){ this.ele.style.left=e.clientX-this.x+“px”; this.ele.style.top=e.clientY-this.y+“px”;

var pos={//存此时的位置 移动的实时位置 x:this.ele.offsetLeft, y:this.ele.offsetTop } //对象转为字符 存进去 只能存字符 //存的位置 localStorage里面去

localStorage.setItem(“qwe”,JSON.stringify(pos)); } up(){ document.οnmοusemοve=document.οnmοuseup=null; } } new Drag();

html2 中:

<div class="box"></div> <script> var obox=document.querySelector(".box"); //初始值 红色的最后存的位置 var pos=JSON.parse(localStorage.getItem("qwe")); obox.style.left=pos.x+"px"; obox.style.top=pos.y+"px"; //localStorage发生改变触发 读取其中的localStorage发生改变 onstorage=function(eve){ var pos=JSON.parse(eve.newValue); // console.log(pos);//对象 x,y obox.style.left=pos.x+"px"; obox.style.top=pos.y+"px"; } class Drag{ constructor() { this.ele=document.querySelector(".box"); this.init(); } init(){ //初始读取位置 var p=JSON.parse(localStorage.getItem("qwe")); this.ele.style.left=p.x+"px"; this.ele.style.top=p.y+"px"; var that=this; this.ele.onmousedown=function(eve){ // var e=eve || window.event; that.x=eve.offsetX; that.y=eve.offsetY; that.down(); } } down(){ var that=this; document.onmousemove=function(eve){ that.move(eve); } document.onmouseup=function(){ that.up(); } } move(e){ this.ele.style.left=e.clientX-this.x+"px"; this.ele.style.top=e.clientY-this.y+"px"; var pos={//存此时的位置 移动的实时位置 x:this.ele.offsetLeft, y:this.ele.offsetTop } //对象转为字符 存进去 只能存字符 //存的位置 localStorage里面去 localStorage.setItem("qwe",JSON.stringify(pos)); } up(){ document.onmousemove=document.onmouseup=null; } } new Drag();
最新回复(0)