我一直在尝试使用 html 中的 javascript 动态更改内容的选择颜色,但似乎无法使其工作。理想情况下,我想将部分颜色更改为任何数组中的一种...
var colors = Array("#A3F8EF", "#FF7275", "#CBB6E7", "#FF9D74", "#FDF874"), idx;
但我什至无法将选择颜色更改为单一不同的颜色。我正在尝试的代码是:
document.styleSheets[0].insertRule('html::-moz-selection {background-color: #FDF874;}',0);
document.styleSheets[0].insertRule('html::selection {background-color: #FDF874;}',0);
document.styleSheets[0].insertRule('html::-webkit-selection {background-color: #FDF874;}',0);
任何想法都会很棒
最佳答案
问题可能是您在解析这些前缀规则之一时遇到异常,因此添加其他规则的代码无法运行。如果将它们放入 try/catch
中,它会起作用:(我还将标签名称从 html
更改为 *
)
例如,以下内容适用于 Chrome、Firefox 和 IE11:
var colors = ["#A3F8EF", "#FF7275", "#CBB6E7", "#FF9D74", "#FDF874"];
setRandomSelectionColor();
function setRandomSelectionColor() {
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
try {
document.styleSheets[0].insertRule("*::-moz-selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
try {
document.styleSheets[0].insertRule("*::selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
try {
document.styleSheets[0].insertRule("*::-webkit-selection {background-color: " + color + ";}", 0);
}
catch (e) {
}
}
<p>Select your text here!</p>
原始答案 (在我好奇为什么失败之前):
我对 insertRule
没有任何运气,但您可以动态创建和替换 style
元素:(我还将标签名称从 html
到 *
)
这适用于 Chrome、Firefox 和 IE11:
var colors = ["#A3F8EF", "#FF7275", "#CBB6E7", "#FF9D74", "#FDF874"];
setRandomSelectionColor();
$("input").on("click", setRandomSelectionColor);
function setRandomSelectionColor() {
var n = Math.floor(Math.random() * colors.length);
var color = colors[n];
$("#the-style").remove();
$("<style id='the-style'>\n" +
"*::-moz-selection {background-color: " + color + ";}" +
"*::selection {background-color: " + color + ";}" +
"*::-webkit-selection {background-color: " + color + ";}" +
"</style>").appendTo('head');
}
<p>Select your text here!</p>
<input type="button" value="New Random Color">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 使用 javascript 操作伪元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30289274/