我想為網站制作一個深色主題,并使用類似于下面的代碼來反轉<body>除影像之外的所有內容的顏色。
我不知道為什么這段代碼不能像我預期的那樣作業:正如你所看到的,即使使用!important,影像也會保持倒置:
body { background-color: grey; }
p { color: white; }
.body {
-webkit-filter: invert(100%);
-moz-filter: invert(100%);
-o-filter: invert(100%);
-ms-filter: invert(100%);
}
img {
-webkit-filter: invert(0%) !important;
-moz-filter: invert(0%) !important;
-o-filter: invert(0%) !important;
-ms-filter: invert(0%) !important;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="body">
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
</div>
<p>The image above should be white</p>
</body>
</html>
我想知道!important實際上有多重要,我應該怎么做才能使影像不倒置。
當然,我不想為網站中的每個影像添加一個類/ID,因為即使我認為這可以解決我的問題,它也不會那么高效和易于閱讀。
uj5u.com熱心網友回復:
嗯,很簡單,你必須再反轉一次!
我們已經學會了-1 * -1= 1,就像這樣:
Inversion*Inversion=Normal!
所以將影像的 0% 設定為 100%,
提示: !important不需要覆寫在它上面定義的規則,這個下面的規則會自動覆寫上面的規則,所以你甚至可以洗掉它。
答案代碼:
body { background-color: grey; }
p { color: white; }
.body {
-webkit-filter: invert(100%);
-moz-filter: invert(100%);
-o-filter: invert(100%);
-ms-filter: invert(100%);
filter: invert(100%);
}
img {
-webkit-filter: invert(100%) !important;
-moz-filter: invert(100%) !important;
-o-filter: invert(100%) !important;
-ms-filter: invert(100%) !important;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="body">
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
</div>
<p>The image above should be white</p>
</body>
</html>
uj5u.com熱心網友回復:
我知道這個問題已經得到解答,并且如前所述,重點是,以這種方式撰寫,您必須執行兩次轉換。這里的要點是,通過反轉顏色來實作暗模式的整個假設是錯誤的。
您所做的只是反轉顏色,您并不一定會使顏色“變暗”。
如果您有一個具有這種顏色的文本怎么辦:

反轉的顏色將是:

這不是某人對黑暗模式的期望。在這種情況下,您將添加另一個“例外”來轉換您的元素并以不同的規則實作它。
我的建議是為亮模式和暗模式定義每個元素的不同版本,這需要做更多的作業,但結果更干凈,最重要的是,更可預測。當然,如果您愿意,也可以使用庫或學習一些最佳實踐來實作暗模式。
uj5u.com熱心網友回復:
問題根本不在于 !important 標簽。
您的第一個 .body 規則集反轉了 body 標簽,它反轉了您的整個網站。這與對所有元素應用反轉不同。
此 .body 規則不適用于每個子元素的反轉,因此影像標簽上沒有反轉,您可以使用 img 規則進行反轉。
您應該做的是將 invert(100%) 應用于您的影像。然后你反轉你的整個網頁,除了影像一次。然后影像被反轉兩次(首先因為身體被反轉,然后在img上被反轉(100%)。反轉兩次與不反轉相同。
uj5u.com熱心網友回復:
您正在將反轉應用于不同的物件。您應該反轉相同的物件。嘗試這個:
body { background-color: grey; }
p { color: white; }
.body {
-webkit-filter: invert(100%);
-moz-filter: invert(100%);
-o-filter: invert(100%);
-ms-filter: invert(100%);
}
.body {
-webkit-filter: invert(0%) !important;
-moz-filter: invert(0%) !important;
-o-filter: invert(0%) !important;
-ms-filter: invert(0%) !important;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="body">
<img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png" />
</div>
<p>The image above should be white</p>
</body>
</html>
您可以將類添加到正文light并將反轉(100%)添加到它并具有不同的類dark并將反轉(0%)添加到它并切換它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442044.html
