任何樣式,javascript都可以操作,讓你所向披靡

前言

習慣了在 css 文件裏面編寫樣式,其實JavaScript 的 CSS對象模型也提供了強大的樣式操作能力,
那就隨文章一起看看,有多少能力是你不知道的吧。

樣式來源

客從八方來, 樣式呢, 樣式五方來。

chrome舊版本用戶自定義樣式目錄: %LocalAppData%/Google/Chrome/User Data/Default/User StyleSheets。 新版本已經不支持用戶自定義樣式。

用戶代理樣式(瀏覽器默認樣式):

至於字體大小,顏色等等,這些都是瀏覽器默認樣式。

前兩種樣式我們一般不會去修改,絕大部分場景我們都是在操作後面三種樣式。

樣式優先級

同一個節點的某個屬性可能被定義多次,最後哪個生效呢? 這是有一個優先級規則的。

內聯樣式 > ID選擇器 > 類選擇器 > 標籤選擇器

細心的同學會問,僞類呢, important呢, 答案也很簡單

  • 僞類 優先級 同 類選擇器
  • important 你最大

到這裏,各位可能都覺得沒問題,那來張圖:

截圖_20245420045437.png

ID選擇器 敗給了 樣式選擇器, 這是因爲 CSS 新的 layer (級聯層) layer1的優先級更高特性導致的, 後續會有專門的文章介紹。

再提個問題: 如果 layer2 修改爲 color: red !important, 那又改顯示什麼顏色呢。

基本知識準備完畢,那就進入下一個階段。

操作元素節點上的style屬性

  • style屬性名是駝峯語法
    想到react給style賦值,是不是呵呵一笑了。
    <style>
        .div {
            background-color: red;
            font-size: 30px;
        }
    </style>
    <script>
        const el = document.getElementById("test-div");
        el.style.backgroundColor = "red";
        el.style.fontSize = "30px";
    </script>
  • style.cssText 批量賦值
  • important! 也是可以生效的
    <div id="test-div">文本</div>
    <style>
        .div {
            background-color: red;
            font-size: 30px;
        }
    </style>
    <script>
        const el = document.getElementById("test-div");
         el.style.cssText ="background-color: green !important; font-size: 40px;"
    </script>

那可不可以直接把style賦值一個對象呢? 很不幸,style是一個只讀屬性,雖然你表面能賦值成功,實際沒有任何變化。

// 例如
document.body.style = {color:"red"};

另外你也可以通過attributeStyleMap屬性來設置style的值:

const buttonEl = document.querySelector("body");
// 更改背景色
buttonEl.attributeStyleMap.set("background-color", 'red');

目前掌握classList的style.cssText的你,是不有點小嘚瑟呢? 這才哪到哪,還有重頭戲。

操作元素節點classList & className屬性

className: 操作的是節點的class屬性。

對比

屬性 方法
className 字符串 字符串具備的方法
classList DOMTokenList 類數組 add, remove, contains, toggle等

沒有classList屬性之前,我們還需要手動封裝類似的方法。 時代的進步真好!

DOMTokenList.toggle

定義: 從列表中刪除一個給定的標記 並返回 false 。 如果標記 不存在,則添加並且函數返回 true。

語法: tokenList.toggle(token, force) ;

force參數: 如果force爲真,就變爲單純的添加。

用兩個按鈕分別來演示toggle true和toggle false.

toggle.gif
代碼如下:

    <div>
        <button type="button" id="btnToggleFalse">toggle(false)</button>
        <button type="button" id="btnToggleTrue">toggle(true)</button>
    </div>

    <div id="container">
        <div>文字</div>
    </div>
    <style>
        .test-div {
            color: red
        }
    </style>

    <script>
        const el = container.firstElementChild;
        // toggle false
        btnToggleFalse.addEventListener("click", function () {
            el.classList.toggle("test-div");
        });
        // toggle true
        btnToggleTrue.addEventListener("click", function () {
            el.classList.toggle("test-div", true);
        })
    </script>

操作style節點內容

本質還是Node節點

style標籤是不是節點,是,那,就可以爲所欲爲!!!

<style>
 	    .div {
            background-color: red;
            font-size: 30px;
        }
</style>

拿到文本內容替換,可不可以,當然是可以的。 劍走偏鋒!

  <div>
        <button id="btnReplace" type="button">替換</button>
    </div>
    <div class="div">
        文本
    </div>
    <style id="ss-test">
        .div {
            background-color: red;
            font-size: 30px;
        }
    </style>
    <script>
        const ssEl = document.getElementById("ss-test");
        btnReplace.addEventListener("click", function () {
            ssEl.textContent = ssEl.textContent.replace("background-color: red", "background-color: blue")
        })
    </script>

動態創建style節點

    <div>
        <button type="button" id="btnAdd">添加style節點</button>
    </div>
    <div class="div">文本</div>

    <script>

        document.getElementById("btnAdd").addEventListener("click", createStyleNode)

        function createStyleNode() {
            const styleNode = document.createElement("style");

            // 設置textContent
            // styleNode.textContent = `
            //     .div {
            //         background-color: red;
            //         font-size: 30px;
            //     }
            // `;
            // append
            styleNode.append(`
                 .div {
                     background-color: red;
                     font-size: 30px;
                 }
            `)
            document.head.appendChild(styleNode);
        }

    </script>

操作已有的style節點

這個就得請專業選手 CSS Object Model 入場, 這是一組允許用JavaScript操縱CSS的API。 它是繼DOM和HTML API之後,又一個操縱CSS的接口,從而能夠動態地讀取和修改CSS樣式。

先看關係(不包含 layer)

截圖_20242120052143.png

現在就做一件事情,把 .div的backgound-color的值從red修改green。從圖上可以看到:

  1. CSSStyleSheet也提供了insertRule和deleteRule的方法
  2. StylePropertyMap提供能操作個規則屬性的能力。

先看效果:

update_ex.gif

那代碼就簡單了:

<div>
    <button type="button" id="btnUpdate">更改style節點</button>
</div>
<div class="div">文本</div>
        <style id="ss-test">
            .div {
                background-color: red;
                font-size: 30px;
            }
            div {
                font-size: 26px
            }
        </style>
<script>
    document.getElementById("btnUpdate").addEventListener("click", updateStyleNode)

    function updateStyleNode() {
        const styleSheets = Array.from(document.styleSheets);
        // ownerNode獲得styleSheet對應的節點
        const st = styleSheets.find(s=> s.ownerNode.id === "ss-test");
        // 選過選擇器找到對應的rule  
        const rule = Array.from(st.cssRules).find(r=> r.selectorText === ".div");

        // 兼容性 
        const styleMap = rule.styleMap;
        styleMap.set("background-color", "blue");

    }
</script>

操作外部引入樣式

動態創建link節點引入樣式

我們首先看一下html頁面裏面通常是怎麼引入樣式的。

<link rel="stylesheet" href="http://x.com/c.css">

其本質依舊是節點,所以我們可以動態的創建節點,掛載到文檔上即可。

function importCSSByUrl(url){
  var link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      document.head.appendChild(link);
}

更改外部引入的樣式

那麼我們外部引入的CSS,我們也能操作嘛?

答案是肯定的,外面引入的樣式最終也會變成一個StyleSheet。 區別在於其href的屬性有其全路徑, 當然也可以通過 onwerNode的值去識別是link 還是 style方式導入的。

所以,幾乎上面的例子,代碼只需少量改動。

function updateStyleNode() {
    const styleSheets = Array.from(document.styleSheets);
    // 通過href判斷
    const st = styleSheets.find(s => s.href.endsWith("2.3.css"));
    const rule = Array.from(st.rules).find(r => r.selectorText === ".div");
    const styleMap = rule.styleMap;
    styleMap.set("background-color", "green");
}

window.getComputeStyle

功能

Window.getComputedStyle()方法返回一個對象,該對象在應用活動樣式表並解析這些值可能包含的任何基本計算後報告元素的所有CSS屬性的值。

語法

let *style* = window.getComputedStyle(*element,* [*pseudoElt*]);

計算後的樣式不等同於css和style裏面設置的樣式

比如font-size屬性和transform屬性:

效果:

代碼:


    <div id="div-test" class="div">
        文本
    </div>
    <hr>
    <div>
        樣式的值
        <pre>
            .div {
                font-size: 1.6rem;
                transform:rotate(3deg);
            }
        </pre>
    </div>
    <hr>
    <div>
        getComputedStyle的值:
        <pre id="divGc"></pre>
    </div>
    <style>
        .div {
            font-size: 1.6rem;
            transform:rotate(3deg);
        }
    </style>

    <script>
        const divEl = document.getElementById("div-test");
        const styleDeclaration = window.getComputedStyle(divEl);
        const fontSize = styleDeclaration.fontSize;
        const transform = styleDeclaration.transform;

        divGc.textContent = `
            fontSize: ${fontSize}
            transform: ${transform}
        `
    </script>

可以獲取僞類樣式

獲取僞類的樣式,就得利用第二個參數

  const styleDeclaration = window.getComputedStyle(divEl, "before");

效果:

代碼:

    <div id="div-test" class="div">
        文本
    </div>

    <hr>
    <div>
        僞類的樣式:
        <pre id="divGc"></pre>
    </div>
    <style>
        .div:before {
            content: '(你好)';
            font-size: 1.6rem;
        }
    </style>

    <script>
        const divEl = document.getElementById("div-test");
        const styleDeclaration = window.getComputedStyle(divEl, "before");
        const fontSize = styleDeclaration.fontSize;
        const content = styleDeclaration.content;

        divGc.textContent = `
            fontSize: ${fontSize}
            content: ${content}
        `
    </script>

此方法會引起重繪

重排:元素的尺寸、結構、或某些屬性發生改變時,瀏覽器重新渲染部分或全部文檔的過程稱爲重排

重繪: 元素樣式的改變並不影響它在文檔流中的位置或者尺寸的時候,例如: color, backgound-color, outline-color等,瀏覽器會重新繪製元素,這個過程稱爲重繪。

這個在之後可能的加餐中詳細說道。

這個是雙刃劍。我們通過例子來認知他,動態創建一個create,想讓他立馬有動畫。

下面的代碼,沒調用 getComputedStyle就不會有動畫, 不取值也沒有動畫

    <div>
        <button id="btnAdd">動態創建節點並動畫</button>
    </div>
    <div id="container">
    </div>
    <style>
        .ani {
            position: absolute;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: blue;
            transition: all 3s;
        }
    </style>
    <script>
        btnAdd.addEventListener("click", createAni);
        function createAni() {
            var div = document.createElement('div')
            div.className = "ani";
            container.appendChild(div);

            div.style.left = "0px";
            // 去掉這行代碼就不會有動畫
            // window.getComputedStyle(div).height
          	// window.getComputedStyle(div) 依舊不會有動畫
            div.style.left = "200px"
        }
    </script>

我們把樣式從內聯樣式,到style節點(標籤),到引入的外部的樣式,挨個揍了一遍,一個能打的都沒有,還有誰。額,不說了,會的交給你們啦,怎麼玩就看你你們啦。

寫在最後

不忘初衷,有所得,而不爲所累,如果你覺得不錯,你的一讚一評就是我前行的最大動力。

微信公衆號:成長的程序世界 ,關注之後,海量電子書,打包拿走不送。

或者添加我的微信 dirge-cloud,一起學習。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章