1. 程式人生 > 其它 >js offset系列屬性

js offset系列屬性

  • offsetParent:返回該元素有定位的父級,如果父級都沒有定位則返回body
  • offsetTop:返回元素相對父級(帶有定位的父級)上方的偏移
  • offsetLeft:返回元素相對父級(帶有定位的父級)左邊框的偏移
  • offsetWidth:返回自身的寬度,包括padding、border、內容區,返回數值不帶單位
  • offsetHeight:返回自身的高度,包括padding、border、內容區,返回數值不帶單位
  • style.width 只能獲取行內樣式的資料,返回有單位,能用js修改數值
  • offsetWidth只能讀不能改,返回無單位

注意:<style></style>要放在js程式碼前面,js中才能正確獲取offset系列屬性。如果style程式碼要放在js程式碼後面,需要使用 window.onload 等待資源載入完畢再執行js程式碼。


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div class="parent">
            <div class="child">child</div>
            <div id="style" style="width: 88px;height: 66px;background-color: #00FFFF;"
> test style </div> </div> </body> <script> window.onload = function(){ /** * offsetParent:返回該元素有定位的父級,如果父級都沒有定位則返回body * * offsetTop:返回元素相對父級(帶有定位的父級)上方的偏移 * offsetLeft:返回元素相對父級(帶有定位的父級)左邊框的偏移 * offsetWidth:返回自身的寬度,包括padding、border、內容區,返回數值不帶單位 * offsetHeight:返回自身的高度,包括padding、border、內容區,返回數值不帶單位 * * style.width 只能獲取行內樣式的資料,返回有單位,能用js修改數值 * offsetWidth只能讀不能改,返回無單位 *
*/ var parent = document.querySelector(".parent"); console.log("parentNode:",parent.parentNode); var child = document.querySelector(".child"); console.log("offsetParent:", child.offsetParent); console.log("offsetTop:", child.offsetTop); console.log("offsetLeft:", child.offsetLeft); console.log("offsetWidth:", child.offsetWidth); console.log("offsetHeight:", child.offsetHeight); console.log("--------------------------------"); var style = document.querySelector("#style"); console.log("offsetWidth:",style.offsetWidth); console.log("style.width:",style.style.width); style.style.width = 111+"px";//這句生效,注意加單位 console.log(style.style.width); style.offsetWidth = 222+"px";//這句不生效 console.log(style.offsetWidth); } </script> <style> * { padding: 0; margin: 0; } .parent { position: relative; display: inline-block; width: 200px; height: 200px; margin: 50px; background-color: #008000; } .child { display: inline-block; position: absolute; width: 50px; height: 50px; margin: 10px; border: 5px solid yellow; background-color: red; } #style{ position: absolute; bottom: 0; right: 0; } </style> </html>

style和offsetWidth的區別:

  • style.width 只能獲取行內樣式的資料,返回有單位,能用js修改數值
  • offsetWidth只能讀不能改,返回無單位