用javascript操纵伪元素

时间:2015-05-17 16:31:20

标签: javascript jquery css

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

任何想法都会很棒

1 个答案:

答案 0 :(得分:4)

问题可能是您正在解析其中一个前缀规则的异常,因此添加其他规则的代码无法运行。如果您将它们放在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>
&#13;
&#13;
&#13;

原始答案 (在我好奇为什么失败之前)

我对insertRule没有任何好运,但您可以动态创建和替换style元素:(我还更改了html的标记名称到*

适用于Chrome,Firefox和IE11:

&#13;
&#13;
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');
}
&#13;
<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>
&#13;
&#13;
&#13;