简体   繁体   English

如何动态地在css文件中添加css?

[英]how to add css in css file dynmically?

i have written a js for grid. 我已经为网格编写了一个js。 gird have a feature where i am taking each column width in input like this. 网格有一个功能,我在这样的输入中获取每个列的宽度。

mygrid._struct = [{ fieldType : "deltaHedgeType", defaultWidth : 80},
           { fieldType : "quoteccy", defaultWidth : 40 }]

So the grid html generate like this 所以网格html会这样生成

<table id="mygrid">
  <tr>
    <td class="deltaHedgeType"></td>
    <td class="quoteccy"></td>
  </tr>
  <tr>
    <td class="deltaHedgeType"></td>
    <td class="quoteccy"></td>
  </tr>
</table>

i want this css to append in style.css 我希望此CSS附加在style.css中

#mygrid .deltaHedgeType{
    width:40;
}
#mygrid .quoteccy{
    width:80;
}

what come in my mind append this css in header in tag. 我想到的是在标签的标头中附加此CSS。 coz IE browser have limitation of count and also its increase the html size of the page. coz IE浏览器的数量有所限制,并且它还会增加页面的html大小。 so how do i append this css in style.css. 所以我如何在style.css中添加此CSS。

You have to parse mygrid._struct to get fieldType and defaultWidth and then for each eleement use following code 您必须解析mygrid._struct以获得fieldType和defaultWidth,然后对每个元素使用以下代码

The final javascript to add css will be 添加CSS的最终JavaScript将是

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '#mygrid.'+fieldType+'{ width:'+defaultWidth+'; }';
document.getElementsByTagName('head')[0].appendChild(style);

For ie limit either use an id on one of the already used style and refere it using jquery or create an new one and append all ur style to this one. 例如,限制要么在一个已经使用的样式上使用一个id,然后使用jquery引用它,要么创建一个新的样式,然后将所有您的样式附加到该样式上。

           $style = $('#MyGridStyle');
          if (!$style[0]) {
            $style = $("<style id='MyGridStyle' type='text/css' rel='stylesheet' />").appendTo($("head"));
          }

now use this $style to add to this 现在使用此$ style添加到此

Refer IE 8 and 7 bug when dynamically adding a stylesheet for another solution 动态添加另一个解决方案的样式表时,请参考IE 8和7错误

您可以将CSS直接写到html页面的开头-我在这里找到了一个很好的例子: 使用JavaScript向<head>添加CSS吗?

在CSS文件内部,您可以使用@import url("/css/filename.css")导入新的CSS文件,该文件会动态刷新并用于某些特殊用途。

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

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