我需要在JavaScript中动态创建一个CSS样式表类,并将其分配给某些HTML元素,如div,table,span,tr等,以及某些控件,如asp:Textbox,Dropdownlist和datalist.
可能吗?
一个样本会很好.
我想返回一个包含CSS规则所有内容的字符串,就像您在内联样式中看到的格式一样.我希望能够在不知道特定规则中包含的内容的情况下执行此操作,因此我不能仅通过样式名称将其拉出(如.style.width等)
CSS:
.test {
width:80px;
height:50px;
background-color:#808080;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止的代码:
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
//this is where I can collect the style information, but how?
}
}
}
getStyle('.test')
Run Code Online (Sandbox Code Playgroud) 我需要检查(在Javascript中)是否加载了CSS文件,如果没有,则加载它.jQuery很好.
我正在使用Greasemonkey并尝试在特定域中添加规则.但它导致错误说The operation is insecure.
该代码在Chrome上正常运行.
该脚本运行http://mydomain.com/test/test.php
并且CSS文件是http://cdn.mydomain.com/test/css/global.css
我的功能:
function css(selector, property, value) {
for (var i=0; i<document.styleSheets.length;i++)
{
try
{
document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
}
catch(err)
{
try // IE
{
document.styleSheets[i].addRule(selector, property+':'+value);
}
catch(err) {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在谷歌上我发现可能是因为我试图访问跨域,所以我尝试将CSS文件的URL添加到"接受的URL"但没有结果.
我该如何解决?