2009-11-12 89 views
215

我需要在JavaScript中動態創建CSS樣式表類,並將其分配給像div,table,span,tr等一些HTML元素,以及一些控件,如asp:Textbox,Dropdownlist和datalist。如何在JavaScript中動態創建CSS類並應用?

可能嗎?

這將是一個很好的例子。

+1

看看https://github.com/Box9/jss – jedierikb 2012-09-07 14:49:19

+0

也http://stackoverflow.com/questions/1212500/jquery-create-見css-rule-class-runtime – jantimon 2012-09-07 15:39:22

回答

284

雖然我不知道你爲什麼要創建CSS類使用JavaScript,這裏是一個選項:

var style = document.createElement('style'); 
style.type = 'text/css'; 
style.innerHTML = '.cssClass { color: #F00; }'; 
document.getElementsByTagName('head')[0].appendChild(style); 

document.getElementById('someElementId').className = 'cssClass'; 
+7

我的用例是一個書籤,它爲QA目的突出顯示某些元素。 – TomG 2011-04-29 19:14:22

+0

我自己的用例是我正在編寫一個深度可配置的jQuery小部件,並且需要能夠應用用戶指定的自定義類,並且我在加載時構建。 – jaydel 2011-05-30 15:00:49

+25

很確定這會導致IE 8及更低版本中出現未知的運行時錯誤。 – 2011-10-31 10:52:43

7

YUI是迄今爲止最好的stylesheet utility我已經看到了在那裏。我建議你檢查出來,但這裏的味道:

// style element or locally sourced link element 
var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query('style',null,true)); 

sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get('local')); 


// OR the id of a style element or locally sourced link element 
sheet = YAHOO.util.StyleSheet('local'); 


// OR string of css text 
var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " + 
      ".moduleX .warn { background: #eec; } " + 
      ".hide_messages .moduleX .alert, " + 
      ".hide_messages .moduleX .warn { display: none; }"; 

sheet = new YAHOO.util.StyleSheet(css); 

顯然還有其他更簡單的動態更改樣式如這裏建議的方式。如果他們對你的問題有意義,他們可能是最好的,但肯定有原因,爲什麼修改CSS是一個更好的解決方案。最明顯的情況是當你需要修改大量元素時。另一個主要的情況是如果你需要你的風格變化來涉及級聯。使用dom修改元素將始終具有更高的優先級。它的大錘方法和等價於直接在html元素上使用style屬性。這並不總是預期的效果。

90

找到了更好的解決方案,其中適用於所有瀏覽器。
使用document.styleSheet添加或替換規則。接受的答案是簡短而方便的,但這在IE8中起作用,而且不太適用。

function createCSSSelector (selector, style) { 
    if (!document.styleSheets) return; 
    if (document.getElementsByTagName('head').length == 0) return; 

    var styleSheet,mediaType; 

    if (document.styleSheets.length > 0) { 
    for (var i = 0, l = document.styleSheets.length; i < l; i++) { 
     if (document.styleSheets[i].disabled) 
     continue; 
     var media = document.styleSheets[i].media; 
     mediaType = typeof media; 

     if (mediaType === 'string') { 
     if (media === '' || (media.indexOf('screen') !== -1)) { 
      styleSheet = document.styleSheets[i]; 
     } 
     } 
     else if (mediaType=='object') { 
     if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) { 
      styleSheet = document.styleSheets[i]; 
     } 
     } 

     if (typeof styleSheet !== 'undefined') 
     break; 
    } 
    } 

    if (typeof styleSheet === 'undefined') { 
    var styleSheetElement = document.createElement('style'); 
    styleSheetElement.type = 'text/css'; 
    document.getElementsByTagName('head')[0].appendChild(styleSheetElement); 

    for (i = 0; i < document.styleSheets.length; i++) { 
     if (document.styleSheets[i].disabled) { 
     continue; 
     } 
     styleSheet = document.styleSheets[i]; 
    } 

    mediaType = typeof styleSheet.media; 
    } 

    if (mediaType === 'string') { 
    for (var i = 0, l = styleSheet.rules.length; i < l; i++) { 
     if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) { 
     styleSheet.rules[i].style.cssText = style; 
     return; 
     } 
    } 
    styleSheet.addRule(selector,style); 
    } 
    else if (mediaType === 'object') { 
    var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0; 
    for (var i = 0; i < styleSheetLength; i++) { 
     if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) { 
     styleSheet.cssRules[i].style.cssText = style; 
     return; 
     } 
    } 
    styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength); 
    } 
} 

功能用法如下。

createCSSSelector('.mycssclass', 'display:none'); 

注意,即使函數名是createClass它實際上創建了一個選擇。所以不要忘記在你的課程名稱前添加(句號)。 無需提及您可以使用此功能創建其他選擇器。
此處發現的http://www.happycode.info/create-css-classes-with-javascript/

+2

確認使用IE8。我不得不在mediaType for-loop ifs中添加一個「styleSheet.cssRules [i] .selectorText &&」和「styleSheet.rules [i] .selectorText &&」,因爲它在Chrome中不起作用,顯然有時候selectorText isn沒有定義。 – w00t 2012-02-15 12:26:22

+0

@ w00t您能否粘貼或編輯代碼以使其工作? – Hengjie 2013-05-17 16:01:11

+1

@恆傑編輯,現在需要進行同行評審。 – w00t 2013-05-18 07:12:13

5

截至IE 9.您現在可以加載文本文件並設置style.innerHTML屬性。所以基本上你現在可以通過ajax加載一個css文件(並獲得回調),然後在這樣的樣式標籤內設置文本。

這可以在其他瀏覽器,不知道多遠回來。但只要你不需要支持IE8,那麼它就會工作。

// RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers. 
$(document).ready(function() { 
    // we want to load the css as a text file and append it with a style. 
    $.ajax({ 
     url:'myCss.css', 
     success: function(result) { 
      var s = document.createElement('style'); 
      s.setAttribute('type', 'text/css'); 
      s.innerHTML = result; 
      document.getElementsByTagName("head")[0].appendChild(s); 
     }, 
     fail: function() { 
      alert('fail'); 
     } 
    }) 
}); 

,然後你可以把它拉外部文件,如myCss.css

.myClass { background:#F00; } 
12

有一盞燈jQuery插件,它允許生成CSS聲明:jQuery-injectCSS

事實上,它使用JSS(由JSON描述的CSS),但爲了生成動態的CSS樣式表,它很容易處理。

$.injectCSS({ 
    "#test": { 
     height: 123 
    } 
}); 
1

使用谷歌關閉:

,你可以只使用ccsom模塊:

goog.require('goog.cssom'); 
var css_node = goog.cssom.addCssText('.cssClass { color: #F00; }'); 

的JavaScript代碼試圖跨瀏覽器把CSS節點插入到文檔頭時。

21

簡短的回答,這是 「在所有瀏覽器」 兼容(具體而言,IE8/7):

function createClass(name,rules){ 
    var style = document.createElement('style'); 
    style.type = 'text/css'; 
    document.getElementsByTagName('head')[0].appendChild(style); 
    if(!(style.sheet||{}).insertRule) 
     (style.styleSheet || style.sheet).addRule(name, rules); 
    else 
     style.sheet.insertRule(name+"{"+rules+"}",0); 
} 
createClass('.whatever',"background-color: green;"); 

而這最後一點的類適用於一個元素:

function applyClass(name,element,doRemove){ 
    if(typeof element.valueOf() == "string"){ 
     element = document.getElementById(element); 
    } 
    if(!element) return; 
    if(doRemove){ 
     element.className = element.className.replace(new RegExp("\\b" + name + "\\b","g")); 
    }else{  
     element.className = element.className + " " + name; 
    } 
} 

這裏有一個小測試頁以及:https://gist.github.com/shadybones/9816763

關鍵的一點是,style元素有一個「styleSheet」/「sheet」屬性,您可以使用它添加/刪除規則。

3

這裏是Vishwanath的解決方案有意見稍微改寫:

function setStyle(cssRules, aSelector, aStyle){ 
    for(var i = 0; i < cssRules.length; i++) { 
     if(cssRules[i].selectorText && cssRules[i].selectorText.toLowerCase() == aSelector.toLowerCase()) { 
      cssRules[i].style.cssText = aStyle; 
      return true; 
     } 
    } 
    return false; 
} 

function createCSSSelector(selector, style) { 
    var doc = document; 
    var allSS = doc.styleSheets; 
    if(!allSS) return; 

    var headElts = doc.getElementsByTagName("head"); 
    if(!headElts.length) return; 

    var styleSheet, media, iSS = allSS.length; // scope is global in a function 
    /* 1. search for media == "screen" */ 
    while(iSS){ --iSS; 
     if(allSS[iSS].disabled) continue; /* dont take into account the disabled stylesheets */ 
     media = allSS[iSS].media; 
     if(typeof media == "object") 
      media = media.mediaText; 
     if(media == "" || media=='all' || media.indexOf("screen") != -1){ 
      styleSheet = allSS[iSS]; 
      iSS = -1; // indication that media=="screen" was found (if not, then iSS==0) 
      break; 
     } 
    } 

    /* 2. if not found, create one */ 
    if(iSS != -1) { 
     var styleSheetElement = doc.createElement("style"); 
     styleSheetElement.type = "text/css"; 
     headElts[0].appendChild(styleSheetElement); 
     styleSheet = doc.styleSheets[allSS.length]; /* take the new stylesheet to add the selector and the style */ 
    } 

    /* 3. add the selector and style */ 
    switch (typeof styleSheet.media) { 
    case "string": 
     if(!setStyle(styleSheet.rules, selector, style)); 
      styleSheet.addRule(selector, style); 
     break; 
    case "object": 
     if(!setStyle(styleSheet.cssRules, selector, style)); 
      styleSheet.insertRule(selector + "{" + style + "}", styleSheet.cssRules.length); 
     break; 
    } 
1

看遍的答案,最明顯,最直接的丟失:使用document.write()寫出CSS的一大塊,你所需要的。

下面是一個例子(查看上codepen:http://codepen.io/ssh33/pen/zGjWga):

<style> 
    @import url(http://fonts.googleapis.com/css?family=Open+Sans:800); 
    .d, body{ font: 3vw 'Open Sans'; padding-top: 1em; } 
    .d { 
     text-align: center; background: #aaf; 
     margin: auto; color: #fff; overflow: hidden; 
     width: 12em; height: 5em; 
    } 
</style> 

<script> 
    function w(s){document.write(s)} 
    w("<style>.long-shadow { text-shadow: "); 
    for(var i=0; i<449; i++) { 
     if(i!= 0) w(","); w(i+"px "+i+"px #444"); 
    } 
    w(";}</style>"); 
</script> 

<div class="d"> 
    <div class="long-shadow">Long Shadow<br> Short Code</div> 
</div> 
+0

這很好,除非你需要在頁面加載或使用XHTML之後創建CSS規則。 – 2016-07-14 09:47:22

0

對於搜索的利益;如果你正在使用jQuery,您可以執行以下操作:

var currentOverride = $('#customoverridestyles'); 

if (currentOverride) { 
currentOverride.remove(); 
} 

$('body').append("<style id=\"customoverridestyles\">body{background-color:pink;}</style>"); 

很明顯,你可以切換到任何你想要的內CSS。

欣賞一些人更喜歡純粹的JavaScript,但它的工作原理和動態寫入/覆蓋樣式非常強大。

2

https://jsfiddle.net/xk6Ut/256/

一個選項,用於動態創建和更新CSS類在JavaScript:

  • 使用樣式元素以創建CSS部分
  • 使用一個ID爲風格的元素,使我們可以更新在CSS

.....

function writeStyles(styleName, cssText) { 
    var styleElement = document.getElementById(styleName); 
    if (styleElement) 
      document.getElementsByTagName('head')[0].removeChild(
     styleElement); 
    styleElement = document.createElement('style'); 
    styleElement.type = 'text/css'; 
    styleElement.id = styleName; 
    styleElement.innerHTML = cssText; 
    document.getElementsByTagName('head')[0].appendChild(styleElement); 
} 

...

var cssText = '.testDIV{ height:' + height + 'px !important; }'; 
    writeStyles('styles_js', cssText) 
2

一個有趣的項目,它可以幫助你在你的任務是JSS

JSS is a better abstraction over CSS. It uses JavaScript as a language to describe styles in a declarative and maintainable way. It is a high performance JS to CSS compiler which works at runtime in the browsers and server-side.

JSS庫允許你使用.attach()功能在DOM /頭部分注入。

Repl online version進行評估。其他information on JSS

一個例子:

// Use plugins. 
jss.use(camelCase()) 

// Create your style. 
const style = { 
    myButton: { 
    color: 'green' 
    } 
} 

// Compile styles, apply plugins. 
const sheet = jss.createStyleSheet(style) 

// If you want to render on the client, insert it into DOM. 
sheet.attach() 
1
function createCSSClass(selector, style, hoverstyle) 
{ 
    if (!document.styleSheets) 
    { 
     return; 
    } 

    if (document.getElementsByTagName("head").length == 0) 
    { 

     return; 
    } 
    var stylesheet; 
    var mediaType; 
    if (document.styleSheets.length > 0) 
    { 
     for (i = 0; i < document.styleSheets.length; i++) 
     { 
      if (document.styleSheets[i].disabled) 
      { 
       continue; 
      } 
      var media = document.styleSheets[i].media; 
      mediaType = typeof media; 

      if (mediaType == "string") 
      { 
       if (media == "" || (media.indexOf("screen") != -1)) 
       { 
        styleSheet = document.styleSheets[i]; 
       } 
      } 
      else if (mediaType == "object") 
      { 
       if (media.mediaText == "" || (media.mediaText.indexOf("screen") != -1)) 
       { 
        styleSheet = document.styleSheets[i]; 
       } 
      } 

      if (typeof styleSheet != "undefined") 
      { 
       break; 
      } 
     } 
    } 

    if (typeof styleSheet == "undefined") { 
     var styleSheetElement = document.createElement("style"); 
     styleSheetElement.type = "text/css"; 
     document.getElementsByTagName("head")[0].appendChild(styleSheetElement); 
     for (i = 0; i < document.styleSheets.length; i++) { 
      if (document.styleSheets[i].disabled) { 
       continue; 
      } 
      styleSheet = document.styleSheets[i]; 
     } 

     var media = styleSheet.media; 
     mediaType = typeof media; 
    } 

    if (mediaType == "string") { 
     for (i = 0; i < styleSheet.rules.length; i++) 
     { 
      if (styleSheet.rules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
      { 
       styleSheet.rules[i].style.cssText = style; 
       return; 
      } 
     } 

     styleSheet.addRule(selector, style); 
    } 
    else if (mediaType == "object") 
    { 
     for (i = 0; i < styleSheet.cssRules.length; i++) 
     { 
      if (styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) 
      { 
       styleSheet.cssRules[i].style.cssText = style; 
       return; 
      } 
     } 

     if (hoverstyle != null) 
     { 
      styleSheet.insertRule(selector + "{" + style + "}", 0); 
      styleSheet.insertRule(selector + ":hover{" + hoverstyle + "}", 1); 
     } 
     else 
     { 
      styleSheet.insertRule(selector + "{" + style + "}", 0); 
     } 
    } 
} 





createCSSClass(".modalPopup .header", 
           " background-color: " + lightest + ";" + 
            "height: 10%;" + 
            "color: White;" + 
            "line-height: 30px;" + 
            "text-align: center;" + 
            " width: 100%;" + 
            "font-weight: bold; ", null); 
+0

上面的代碼crate css動態避免添加代碼只能回答 – tushar 2017-03-07 18:40:36

+2

回答 – zombie 2017-03-07 19:12:47