gpt4 book ai didi

javascript - 使用javascript操作伪元素

转载 作者:行者123 更新时间:2023-11-29 18:07:24 25 4
gpt4 key购买 nike

我一直在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com