HTML定位插件是一種十分實用的工具,它可以幫助我們在網頁制作過程中更加方便地定位元素。下面是一段HTML代碼實現該插件的方式:
function $(id) { return document.getElementById(id); } function getStyle(obj,attr) { return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr]; } function getPosition(obj){ var left = obj.offsetLeft; var top = obj.offsetTop; while(obj.offsetParent){ obj = obj.offsetParent; left += obj.offsetLeft; top += obj.offsetTop; } return {x:left,y:top}; } function addEvent(obj,event,fn) { if(obj.addEventListener){ obj.addEventListener(event,fn,false); }else{ obj.attachEvent('on'+event,fn); } } function removeEvent(obj,event,fn) { if(obj.removeEventListener){ obj.removeEventListener(event,fn,false); }else{ obj.detachEvent('on'+event,fn); } } function Drag(obj) { this.obj = obj; this.disX = 0; this.disY = 0; var _this = this; addEvent(this.obj,'mousedown',function(ev){ var ev = ev || event; _this.fnDown(ev); return false; }); } Drag.prototype.fnDown = function(ev) { var _this = this; this.disX = ev.clientX - getPosition(this.obj).x; this.disY = ev.clientY - getPosition(this.obj).y; addEvent(document,'mousemove',this.fnMove); addEvent(document,'mouseup',this.fnUp); } Drag.prototype.fnMove = function(ev) { var ev = ev || event; this.obj.style.left = ev.clientX - this.disX + 'px'; this.obj.style.top = ev.clientY - this.disY + 'px'; } Drag.prototype.fnUp = function() { removeEvent(document,'mousemove',this.fnMove); removeEvent(document,'mouseup',this.fnUp); }以上就是一個簡單的HTML定位插件函數。使用時,我們只需在HTML代碼中引用上述代碼,然后為需要定位的元素綁定Drag對象即可。通過此插件,我們可以更快捷地實現網頁中元素的定位等操作。