我正在开发浏览器扩展,部分功能需要将随机类名添加到我定位的元素中,并将CSS应用于这些元素..特别是CSS伪选择器“:focus”。
我有几个功能可以正常工作,但是如果你运行几次脚本,应用CSS的函数就会失败,因为它需要来自第一个尚未完成的函数的数据。我一直在阅读有关回调的内容,似乎可以在这里使用它来使其正常工作,但我真的无法理解如何使它工作。
这是代码:(一次又一次刷新输出,它打破~1:10次)
JSBin :http://jsbin.com/jibas/1/edit
// random string generator
function uniqueClassName(L){
var s= '';
var randomchar=function(){
var n= Math.floor(Math.random()*62);
if(n<10) return n; //1-10
if(n<36) return String.fromCharCode(n+55); //A-Z
return String.fromCharCode(n+61); //a-z
};
while(s.length< L) s+= randomchar();
return s;
}
// generate a random class name
var thisBoxNewClass = uniqueClassName(24);
// append the random class name to the 'a' tag;
document.getElementById('hi').className += thisBoxNewClass;
// apply a ':focus' css style to the newly generated class name
function appendStyle(styles) {
var css = document.createElement('style');
css.type = 'text/css';
css.appendChild(document.createTextNode(styles));
document.getElementsByTagName("head")[0].appendChild(css);
}
// the style that is going to be targeted to the class with the random name
// (it doesnt always work)
// and a global style that doesnt rely on the random string generator
// (always works)
var styles = 'a.' + thisBoxNewClass + ' { color: #0f0 !important }';
styles += 'body { color: red !important}';
// run it
window.onload = function() { appendStyle(styles); };
如果您多次运行此脚本,请注意'hello'文本并不总是变为绿色。我想也许我可以设置一个条件,等到thisBoxNewClass等于undefined以外的东西,然后运行appendStyle函数,但这也没有用。它几乎看起来像一个浏览器错误,但它很奇怪,因为它发生在我尝试过的每个浏览器中。不太清楚这笔交易是什么。任何解决方案都将不胜感激。
答案 0 :(得分:4)
非常确定你的问题是你的随机字符串生成器偶尔会吐出无效的CSS类名。
例如,我看到你的代码运行失败了,生成的类是“4Qzec5gP8Gk7zg7mN8KCbeAs”。从数字开始 - 在这种情况下,4 - 无效,浏览器忽略该规则。