简体   繁体   中英

how to add css in css file dynmically?

i have written a js for grid. 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

<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

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

what come in my mind append this css in header in tag. coz IE browser have limitation of count and also its increase the html size of the page. so how do i append this css in style.css.

You have to parse mygrid._struct to get fieldType and defaultWidth and then for each eleement use following code

The final javascript to add css will be

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.

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

now use this $style to add to this

Refer IE 8 and 7 bug when dynamically adding a stylesheet for another solution

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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