您好,登錄后才能下訂單哦!
html:
<!DOCTYPE html> <html> <head> <meta charset= "utf-8"> <title></title> <!--<script src="jquery-1.9.1.min.js"></script>--> <style> #drag{ background: red; width: 200px; height: 200px; cursor: move; position: fixed; top: 0; left: 0; } </style> </head> <body> <div id="drag"></div> <script src="scripts/test.js"></script> </body> </html>
js:
window.onload = function(){ var drag = new Drag("drag"); drag.init(); } //獲取瀏覽器窗口寬度 function getInner(){ var pageWidth = window.innerWidth; var pageHeight = window.innerHeight; if(typeof pageWidth != "number"){ if(document.compatMode == "CSS1Compat"){ pageWidth = document.documentElement.clientWidth; pageHeight = document.documentElement.clientHeight; }else { pageWidth = document.body.clientWidth; pageHeight = document.body.clientHeight; } } return {width:pageWidth,height:pageHeight}; } //構造函數 function Drag(id){ this.obj = document.getElementById("drag"); this.disx = 0; this.disy = 0; } Drag.prototype.init = function(){ //this 指針 var me = this; this.obj.||event; me.onmouseDown(e); //阻止默認事件 return false; } } Drag.prototype.onmouseDown = function(e){ //this指針 var me = this; this.disx = e.clientX - this.obj.offsetLeft; this.disy = e.clientY - this.obj.offsetTop; document.||event; me.onmouseMove(e); } document.onmouseup = function(){ me.mouseUp(); } } Drag.prototype.onmouseMove = function (e){ //this指針 var lf = e.clientX - this.disx; var tp = e.clientY - this.disy; if(lf < 0){ //防止拖曳層超出左邊界 lf = 0; }else if(lf > getInner().width - this.obj.offsetWidth){ lf = getInner().width - this.obj.offsetWidth;//防止拖曳層超出右邊界 } if(tp < 0){ tp = 0;//防止拖曳層超出上邊界 }else if(tp > getInner().height - this.obj.offsetHeight){ tp = getInner().height - this.obj.offsetHeight;//防止拖曳層超出下邊界 } this.obj.style.left = lf + 'px'; this.obj.style.top = tp + 'px'; }; Drag.prototype.mouseUp = function (){ document.onmousemove = null; document.onmouseup = null; };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。