js中獲取元素的當前位置
js中獲取當前位置有如下幾種方法:
event.offsetX, (IE屬性,測試都可以使用)
event.offsetY, (IE屬性,測試都可以使用)
event.clientX,
event.clienY,
event.scrennX,
event.screenY,
他們的區別如下:
可以看出,
event.screenX和event.screenY是相對於顯示屏的位置。
event.clientX和event.clientY是相對於瀏覽器的位置。
event.offsetX和event.offsetY是相對於元素的位置。
另外,obj.style.width和obj.offsetWidth以及obj.clientWidth的區別
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style type="text/css"> .d{ width:200px; height:200px; border:10px #ccc solid; padding:10px; background:red; } </style> </head> <body> <div class="d"></div> </body> <script type="text/javascript"> var d = document.getElementsByClassName('d')[0]; console.log(d.clientWidth); //220 console.log(getComputedStyle(d,null).width); //200px console.log(d.offsetWidth); //240 <span style="white-space:pre"> </span>console.log(d.style.width); //undefined </script> </html>
這裡,
obj.style.width; //undefined; (這種方式是獲取content區的寬度,並且是隻能獲取行內樣式!)
getComputedStyle(d,null).width; //200px 是獲取的字串,如果要計算的話,是需要parseInt的
obj.clientWidth = 200(content區寬度) + 10X2(兩邊的padding) = 220
obj.offsetWidth = 200(content區寬度) + 10X2(兩邊的padding) + 10X2(兩邊的border) = 240
另外一個獲取位置的屬性時,window物件下面的innerHeight,innerWidth,outerHeight,outerWidth
其中,innerHeight,innerWidth是瀏覽器可視視窗的高度和寬度,不包括上面的位址列和下面的廣告欄,僅僅是指網頁的高度和寬度。
而outerHeight,outerWidth是返回的是包括位址列,標籤頁以及下面的廣告欄的高度和寬度。