簡體   English   中英

更改所有元素的顏色

[英]Change the color of all elements

我希望更改網站的“口音”顏色。 有誰知道一種有效的方法來更改所有元素的背景顏色、顏色和邊框顏色,例如顏色為“洋紅色”? 有沒有辦法檢測 CSS 文件中的屬性洋紅色並將其替換為另一種顏色? 我正在為一個網站構建一個擴展(並且不希望附加一個帶有顏色變化的大量 CSS 文件)並且不能更改網站的源代碼。

如果有什么不清楚的,請隨時詢問。

您可以使用 jQuery .css()方法更改多個 css 屬性:

$(".yourCssSelector").css({
    "background-color": "magenta",
    "color": "#00FF00",
    "border-color": "blue"
});

或使用香草JS:

// choose an element using any of these:
var elem = document.getElementById('your-id');
var elem = document.getElementsByClassName('your-class-name')[0];
var elem = document.getElementsByTagName('div')[1]; // indexes are for example

elem.style.borderColor = 'blue';
elem.style.backgroundColor = 'magenta';
elem.style.color = '#00FF00';

是的,它將需要許多 CSS 更改。 你想改變整個網站的外觀——當然,它會的。 我不認為您網站的設計者通過內聯樣式將每個元素都塗上了magenta - 存在樣式,明智地選擇選擇器和類,您將很容易做到這一點。

你可以做這樣的事情。 循環遍歷所有元素,如果計算出的顏色是洋紅色,則在元素上設置新顏色。

var elems = document.body.getElementsByTagName("*"),
    oldColor = "rgb(255, 0, 255)",
    newColor = "rgb(0, 0, 0)";

function getValue (elem, property) {
    return window.getComputedStyle(elem, null)
        .getPropertyValue(property);
}

Array.prototype.forEach.call(elems, function (elem) {
    var backgroundColor = getValue(elem, "background-color"),
        borderColor = getValue(elem, "border-color"),
        color = getValue(elem, "color");

    if (backgroundColor == oldColor) {
        elem.style.backgroundColor = newColor;
    }

    if (borderColor == oldColor) {
        elem.style.borderColor = newColor;
    }

    if (color == oldColor) {
        elem.style.color = newColor;
    }    
});

 function changeColors () { var elems = document.body.getElementsByTagName("*"), oldColor = "rgb(255, 0, 255)", newColor = "rgb(0, 0, 0)"; function getValue (elem, property) { return window.getComputedStyle(elem, null) .getPropertyValue(property); } console.log(elems); [].forEach.call(elems, function (elem) { var backgroundColor = getValue(elem, "background-color"), borderColor = getValue(elem, "border-color"), color = getValue(elem, "color"); if (backgroundColor == oldColor) { elem.style.backgroundColor = newColor; } if (borderColor == oldColor) { elem.style.borderColor = newColor; } if (color == oldColor) { elem.style.color = newColor; } }); }
 .magenta-background { color: white; background-color: magenta; } .magenta-color { color: magenta; } .magenta-border { border: solid 2px magenta; }
 <body> <div class="magenta-background">Magenta Background</div> <div class="magenta-color">Magenta text</div> <div class="magenta-border">Magenta border</div> <button onclick="changeColors()">Change Colors</button> </body>

如果有其他選擇,我不建議這樣做。 預先更改 CSS 將是理想的,並且根本不使用 JS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM