1. 程式人生 > >js中獲取css樣式 getComputedStyle

js中獲取css樣式 getComputedStyle

在js中直接用點方法是沒有辦法獲取到外鏈式、內嵌式的樣式表。只能夠獲取到行內樣式,然後就誕生了這篇部落格。

一、js中獲取行內樣式

在js中直接獲取css的樣式,只能獲取到行內樣式表。具有兩種方法,程式碼如下:

   <div id="myDiv" style = "width:100px; height:100px; 
   background-color:red; border:1px solid black"></div>

<script>
    var myDiv = document.getElementById('myDiv');
     alert(myDiv.style.width);      				 //100px
    alert(myDiv.style['height']);  				 //100px
     alert(myDiv.style.backgroundColor);  	        //red

</script>

在這裡注意呼叫的方法,直接用點方法,或者用[‘屬性名’]來獲取

二、js中獲取外鏈css方法

在外鏈或者是內嵌的樣式表中,無法使用點方法等方法來獲取css的屬性,只能夠用下面一種方法:
window.getComputedStyle(element,當前元素的偽類),在最新版中,已經拋棄了偽元素的使用,在早期版本中一般用null進行表示。因此一般採用:
window.getComputedStyle(element);

element表示的是所要獲取的元素的樣式,此時輸出的是一個物件,此物件中包含的是一個元素中的所有樣式,無論是否使用。
呼叫程式碼如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            padding:30px;
            background-color: palegreen;
            background-position:-24px;
        }
    </style>
</head>
<body>
        <div class="box"></div>
</body>
</html>
<script>
    box = document.querySelector('.box');
    console.log(window.getComputedStyle(box));
</script>

輸出如下格式:
在這裡插入圖片描述
輸出的是一個物件,具有許多的樣式,就不截圖出來了,很多很多,現在說如何獲取自己想要的樣式。

獲取所需的樣式:
只需要使用點方法就可以呼叫屬性方法啦,比如:window.getComputedStyle(box).padding; 這個時候就能夠輸出元素設定的paading值。
此時獲取到的數值全部都是字串的形式,背景顏色輸出的是rgb的值
在呼叫的時候,要小心使用,因為是字串的形式。並且背景顏色輸出的是rgb的值哦,注意使用,每一次要呼叫的時候,可以先輸出一下,看一下到底是什麼格式,比較方便啦~

具體程式碼:

box = document.querySelector('.box');
    // console.log(window.getComputedStyle(box));
    var obj= window.getComputedStyle(box);
    console.log(obj.padding);        //30px
    console.log(obj.backgroundColor);    //red ----rgb(255,0,0)

** 三、兩種的區別**

element.style.attr ------ 這種方法是可讀可寫的,也就是能夠改變樣。只能夠獲取行內樣式,獲取其他格式的時候是輸出為空的。但是如果是在js中,重新對樣式進行賦值,是可以獲取到的,因為js中新增css樣式,是新增到行內樣式上的,即:box.style.width = 200+‘px’ ,此時是可以獲取並修改的,因為是行內樣式。
window.getComputedStyle(element)----只可讀,只能夠獲取,不能夠修改樣式。

四、最簡單的方法–JQ

具體程式碼如下:

//jquery方法
const jq_width = $('.box').css('width');
const jq_lineHeight = $('.box').css('line-height');
console.log(jq_width,jq_lineHeight);//200px 150px

最後要告訴自己,腦子不轉,真的會變笨的!!!