需求:使用JavaScript,在input輸入框被點擊時獲取input座標的絕對位置,this
原理:根據js中的元素offsetLeft、offsetTop獲取相對於父元素的X、Y座標相對位置,而後遍歷到最頂層的body元素,逐步疊加距離,最終獲取的位置即爲input的絕對位置。code
代碼以下:ip
//獲取x座標 function getXPosition(e){ var x=e.offsetLeft; while(e=e.offsetParent) { x+=e.offsetLeft; } return x-260;//-260防止屏幕超出 } //獲取y座標 function getYPosition(e){ var y=e.offsetTop; while(e=e.offsetParent) { y+=e.offsetTop; } return y+80;//80爲input高度 } //調用 $(".input").on("click",function(event){ alert("x:"+getXPosition(this)+",Y:"+getYPosition(this)); });