通过JS将CSS附加到随机生成的类名中是需要的回调

Appending CSS to a randomly generated class name via JS -- is a callback needed?

本文关键字:回调 CSS JS 随机 通过      更新时间:2023-09-26

我正在进行浏览器扩展,部分功能需要向我要定位的元素添加随机类名,并将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等于未定义以外的值,然后运行appendStyle函数,但这也不起作用。这看起来几乎像是一个浏览器错误,但它很奇怪,因为它发生在我尝试过的每一个浏览器中。不太确定交易是什么。任何解决方案都将不胜感激。

很确定您的问题是您的随机字符串生成器偶尔会吐出无效的CSS类名。

例如,我看到您的代码运行失败,生成的类是"4Qzec5gP8Gk7zg7mN8KCbeAs"。以数字开头(在本例中为4)是无效的,浏览器会忽略该规则。