當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML DOM offsetWidth用法及代碼示例


DOM offsetWidth屬性用於以整數形式返回元素的布局寬度。以像素為單位。它包括寬度,邊框,填充和垂直滾動條,但不包括邊距。如果元素是隱藏的,則返回0。

用法:

element.offsetWidth

返回值:它以整數形式返回元素的布局寬度。


範例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        DOM Style offsetWidth Property 
    </title> 
  
    <style> 
        #GFG { 
            height:150px; 
            width:300px; 
            padding:10px; 
            margin:15px; 
            background-color:green; 
        } 
    </style> 
</head> 
  
<body> 
    <h2>DOM Style offsetWidth Property</h2> 
  
    <div id="GFG"> 
        <b>Information about this div:</b> 
  
        <p id="demo"></p> 
    </div> 
  
    <button type="button" onclick="Geeks()"> 
        Submit 
    </button> 
  
    <script> 
        function Geeks() { 
  
            var elmnt = document.getElementById("GFG"); 
  
            var txt = "Width including padding and border:" 
            + elmnt.offsetWidth + "px"; 
  
            document.getElementById("demo").innerHTML = txt; 
        } 
    </script> 
</body> 
  
</html>

輸出:
之前單擊按鈕:

單擊按鈕後:

範例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        DOM Style offsetWidth Property 
    </title> 
  
    <style> 
        #GFG { 
            height:150px; 
            width:300px; 
            padding:10px; 
            margin:15px; 
            background-color:green; 
        } 
    </style> 
</head> 
  
<body> 
    <h2>DOM Style offsetWidth Property</h2> 
  
    <div id="GFG"> 
        <b>Information about this div:</b> 
        <br> 
  
        <p id="demo"></p> 
    </div> 
  
    <button type="button" onclick="Geeks()"> 
        Submit 
    </button> 
  
    <script> 
        function Geeks() { 
            var elmnt = document.getElementById("GFG"); 
            var txt = ""; 
            txt += "Width with padding:" 
                + elmnt.clientWidth + "px<br>"; 
  
            txt += "Width with padding and border:" 
                + elmnt.offsetWidth + "px"; 
  
            document.getElementById("demo").innerHTML = txt; 
        } 
    </script> 
</body> 
  
</html>    

輸出:
之前單擊按鈕:

單擊按鈕後:

支持的瀏覽器:下麵列出了DOM offsetWidth屬性支持的瀏覽器:

  • 穀歌瀏覽器
  • IE瀏覽器
  • 火狐瀏覽器
  • Opera
  • 蘋果瀏覽器


相關用法


注:本文由純淨天空篩選整理自sarthak_ishu11大神的英文原創作品 HTML | DOM offsetWidth Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。