JS控制CSS偽元素的方法(上)
阿新 • • 發佈:2018-10-31
宣告:此方法由bumfod 同學提供
【HTML部分】
<!DOCTYPE html>
<title>CSS</title>
<article>The seller can, under Business Law <ref>1782</ref>, offer a full refund to buyers. </article>
【CSS部分】
body {
font: 200%/1.45 charter;
}
ref::before {
content: '\00A7';
letter-spacing: .1em;
}
【JavaScript部分】
function ruleSelector(selector) {
function uni(selector) {
return selector.replace(/::/g, ':')
}
return Array.prototype.filter.call(Array.prototype.concat.apply([], Array.prototype.map.call(document.styleSheets, function (x) {
return Array.prototype.slice.call(x.cssRules);
})), function(x) {
return uni(x.selectorText) === uni(selector);
});
}
var toggle = false,
pseudo = ruleSelector("ref::before").slice(-1);
document.querySelector("article").onclick = function () {
pseudo.forEach(function(rule) {
if (toggle = !toggle)
rule.style.color = "red";
else
rule.style.color = "black";
});
}
最終,你在頁面上看到這句話的時候
The seller can, under Business Law 1782, offer a full refund to buyers.
就會出現以下效果:
點選前:
點選後:
總結:
這是一種相當hack的方法,適合高逼格青年。遍歷了所有的css,找到偽元素,然後更改
下篇我們再來說一說普通青年的做法