简体   繁体   English

在javascript / jquery中获取CSS规则

[英]fetch CSS rules in javascript/jquery

i want the rules of css to be fetched and displayed in drop down for this i am doing.. 我想为此获取css的规则并在下拉菜单中显示。

var opnr = window.opener ; 
function getStyle() { 
    var selCss=opnr.document.getElementById("CSS");
    loadjscssfile("css/"+selCss.value,"css");
    var cssRef = document.styleSheets[0];
    cssRef.href ='css/'+ selCss.value;
    var classes = cssRef.rules || cssRef.cssRules ;
    var select = document.getElementById('stylefieldid');//document.createElement('select');

    for(var x=0;x<classes.length;x++) { 
       var option = document.createElement('option');
       var className = classes[x].selectorText;
       if(className.startsWith('.')){
           className = className.substring(1,className.length);
       }
          option.text = className;
          option.value = className;
       select.add(option);
    } 
} 


function loadjscssfile(filename, filetype){
    var fileref; 
    if (filetype=="js")
    {
        fileref=document.createElement("script");
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    } 
    else if (filetype=="css"){
        fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    } 
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

but this is showing abrupt behaviour the variable classes comes to be undefined sometimes while it has value sometimes... i tried alerting cssRef.href it gives me correct value.. 但是,这显示了突然的行为,有时变量classes有时会变得不确定,而有时却有价值...我试图提醒cssRef.href它给了我正确的值。

the code is not at all working on FF any work around 该代码在FF上根本不起作用

Any help on this?? 任何帮助吗? why its happening like this 为什么会这样发生

any alternative in jquery???? 在jQuery中有其他选择吗????

Are you sure your code is firing after the page has loaded? 您确定页面加载后会触发代码吗? Try calling it after your code in the <body onload="someFunction()"> or at the bottom of the page 尝试在<body onload="someFunction()">或页面底部调用它

Done it using css parser on server side and passed the list to jsp page... and is working on all modern day browsers.. 使用服务器端的css解析器将其完成,并将列表传递给jsp页面...,并且适用于所有现代浏览器。

Thanks for the reply :) 谢谢回复 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM