写了一个拖拽函数,想通过闭包的方式让index公有化,在这不同的obj设置拖拽的时候,他们共用一个zindex
代码如下
/*拖拽函数,限定范围为整个窗口内 */function drag(obj){ var _this = this; var zindex = 100; return function(){ obj.onmousedown = function(e){ var e = e || window.event; var disX = e.clientX - this.offsetLeft; var disY = e.clientY - this.offsetTop; console.log(zindex); //zindex++; obj.style.zIndex = zindex++; if(obj.setCapture){ obj.setCapture(); obj.onmousemove = mouseMove obj.onmouseup = mouseUp; }else{ document.onmousemove = mouseMove; document.onmouseup = mouseUp; } return false; function mouseMove(e){ var e = e || window.event; var l = e.clientX - disX; var t = e.clientY - disY; if(obj.setCapture){ obj.setCapture(); } //console.log(e.clientX); if(l<=-obj.parentNode.getBoundingClientRect().left){ l = -obj.parentNode.getBoundingClientRect().left; }else if(l>= viewW()- obj.offsetWidth- obj.parentNode.getBoundingClientRect().left){ l = viewW()- obj.offsetWidth - obj.parentNode.getBoundingClientRect().left; } if(t<=-obj.parentNode.getBoundingClientRect().top){ t = -obj.parentNode.getBoundingClientRect().top; }else if(t>= viewH()- obj.offsetHeight- obj.parentNode.getBoundingClientRect().top){ t = viewH()- obj.offsetHeight - obj.parentNode.getBoundingClientRect().top; } obj.style.left = l + 'px'; obj.style.top = t + 'px'; } function mouseUp(){ if(obj.releaseCapture){ obj.releaseCapture(); } this.onmousemove = null; this.onmouseup = null; } }; }}
代码如下
/*拖拽函数,限定范围为整个窗口内 */function drag(obj){ var _this = this; var zindex = 100; return function(){ obj.onmousedown = function(e){ var e = e || window.event; var disX = e.clientX - this.offsetLeft; var disY = e.clientY - this.offsetTop; console.log(zindex); //zindex++; obj.style.zIndex = zindex++; if(obj.setCapture){ obj.setCapture(); obj.onmousemove = mouseMove obj.onmouseup = mouseUp; }else{ document.onmousemove = mouseMove; document.onmouseup = mouseUp; } return false; function mouseMove(e){ var e = e || window.event; var l = e.clientX - disX; var t = e.clientY - disY; if(obj.setCapture){ obj.setCapture(); } //console.log(e.clientX); if(l<=-obj.parentNode.getBoundingClientRect().left){ l = -obj.parentNode.getBoundingClientRect().left; }else if(l>= viewW()- obj.offsetWidth- obj.parentNode.getBoundingClientRect().left){ l = viewW()- obj.offsetWidth - obj.parentNode.getBoundingClientRect().left; } if(t<=-obj.parentNode.getBoundingClientRect().top){ t = -obj.parentNode.getBoundingClientRect().top; }else if(t>= viewH()- obj.offsetHeight- obj.parentNode.getBoundingClientRect().top){ t = viewH()- obj.offsetHeight - obj.parentNode.getBoundingClientRect().top; } obj.style.left = l + 'px'; obj.style.top = t + 'px'; } function mouseUp(){ if(obj.releaseCapture){ obj.releaseCapture(); } this.onmousemove = null; this.onmouseup = null; } }; }}