js擷取、設定元素css屬性值__JavaScript

來源:互聯網
上載者:User

這裡以擷取html元素寬高為例

js擷取html元素寬高有兩種方法:1.obj.style.width;2.getComputedStyle和currentStyle(IE)函數

但實際操作上會發現,第一種方法是無法擷取到行內設定的元素屬性值的,使用obj.offsetWidth即可,樣式可以anywhere(合理的)。(使用obj.offsetWidth;擷取到的是容器當前大小,包括邊(border)和內填充(padding)的值,不包括margin)。
使用getComputedStyle和currentStyle(IE)函數來擷取樣式屬性,可封裝如下的函數:

function getStyle(obj,attr){  if(obj.currentStyle){//ie    return obj.currentStyle[attr];  }else{    return getComputedStyle(obj)[attr];  }}
直接調用這個函數就可以了。

getComputedStyle方法具有可選的第二個參數,針對於虛擬元素,可參考:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.