我正在使用瀏覽器擴展,部分功能需要爲我定位的元素添加隨機類名,並將CSS應用於這些元素。特別是CSS僞選擇符「:focus」。通過JS將CSS附加到隨機生成的類名 - 是否需要回調?
我有幾個函數可以一起正常工作,但是如果您運行腳本幾次,則應用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); };
如果您運行此腳本幾次,通知'你好'的文字並不總是變綠。我想也許我可以設置一個條件來等待,直到這個BoxNewClass等於undefined之外的其他東西,然後運行appendStyle函數,但那也行不通。它幾乎看起來像一個瀏覽器錯誤,但它很奇怪,因爲它發生在我嘗試過的每個瀏覽器中。不確定交易是什麼。任何解決方案將不勝感激。
所有你需要做的事情就是將'var s ='';'改變爲'var s ='任何字母';'; – rafaelcastrocouto 2014-10-03 00:21:36
男人 - 甚至不知道這一點。我從來沒有抓到過。非常感謝。 – fanfare 2014-10-03 00:24:21