2012-11-13 11 views
7

コンテンツを生成した後にスタイルタグを変更したい。 スタイルタグにスタイルを追加するにはどうすればよいですか? 私が使用してみました:JavaScriptを使用してスタイルタグを動的に変更するにはどうすればよいですか?

document.getElementById('style').appendChild(styleContents); 

をそれは

+0

スタイルタグは要素を含むことになっていません –

+0

何ですかあなたはやろうとしていますか?要素のCSSスタイルを変更しますか? – danwellman

+0

可能な複製:http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript –

答えて

11

を試してみてください。これは、使用して達成することができる。

document.getElementsByTagName('style')[0].innerHTML=""; //some css goes here 

あなたはまた、使用することができます。

document.styleSheets[0].cssText = ""; //some css goes here 
6

styleが財産である動作しませんでした。 getElementById()の後は、styleを変更できます。

HTML:

<div id='myDiv'>...</div> 

JS:

var div = document.getElementById('myDiv') 

div.style.background = 'red'; 
div.style.margin = "10px"; 
div.style.fontSize = "12px"; 

など

+3

これは間違っています。彼はスタイルタグを変更したいので、これはインラインスタイルをdivに適用します。これは無関係です。 –

+0

こんにちはスティーブ、これは属性値を割り当てる正当な方法ですが、それを行うには組み込み関数を使うことをお勧めします。異なるブラウザでHTMLとJSをレンダリングするさまざまな方法が原因です。私もこれまでこれをやっていましたが、特にIEで多くの問題に直面しました。 – Yash

+0

どのような組み込み関数がありますか? – Ben

1

あなたはjQueryライブラリを使用すると、直接DOM要素に新しいCSSを追加していないのはなぜ?例えば

<script> 
$(document).ready(function(){ 
    $("#an_element").css("border", "1px solid #333"); 
}); 
</script> 

<div id="an_element">Test</a> 

これは、ID "an_element" であなたの要素の周囲に境界線を追加します。

jQuery Selectors

jQuery CSS

2

おそらくスタイルタグにCSSを追加しようとしている。この

var currentElement = document.getElementById('style'); 
var currentStyle = currentElement.getAttribute('style'); 
var stylePieces = []; 
if(currentStyle) { 
    stylePieces = currentStyle.split(';'); 
} 
stylePieces.push('new-style: true;'); 
currentElement.setAttribute('style', stylePieces.join(';')); 
3

style要素がどの要素の子を持っていない、その内容は単なるテキスト定義であるとして(限りHTMLが懸念しています)。しかし、これは、innerHTMLプロパティを使用してコンテンツに追加できることを意味します。あなたの要素が<style id=foo>を持っている場合は、書き込み:

document.getElementById('foo').innerHTML += styleContents; 
3

私はhttp://jsfiddle.net/fttS5/1/で一緒に簡単な例を投げました。

HTMLの他の要素と同じように、スタイルタグにidを付けることができます。

<style id="style"></style>

今あなたがのappendChildを試みたコードを取得し、トリックを行う必要があり、それ

document.getElementById('style').appendChild(document.createTextNode(styleContents));

この1つのクイックチェンジを追加することができます。がんばろう。

また、以下の回答に記載されているinnerHTMLメソッドを使用することもできます。

6

これは古い質問ですが、私は要素に直接スタイリングを適用することなくこれらを動的に更新する方法を見つけようとしています。

スタイルタグにIDを付けて選択すると、シートプロパティを使用してそのCSSにアクセスできます。

ここから必要なものを更新できます。タグ内のCSS全体を置き換えるか、個々のクラスを更新する。

document.getElementById('somestyletagid').sheet.cssRules[0].selectorText 

これはクラスセレクタです。

document.getElementById('somestyletagid').sheet.cssRules[0].style 

これらはすべて、そのクラスの個々のCSSプロパティです。

あなたはこれを行うことにより、背景色を更新することができます。

document.getElementById('somestyletagid').sheet.cssRules[0].style.backgroundColor = 'red' 

これは、あなたのHTML内の任意のスタイルタグにアクセスする方法です。残念ながら、私が見つけることができるCSSStyleRuleごとに厳密に一意のIDはありません。最も近いのはselectorTextですが、明らかにそれを繰り返すことができます。いずれにしても、少なくとも私のニーズに対しては、これは私が必要とするものとまったく同じです。

また、含まれているCSSファイルをdocument.styleSheetsを使用して更新し、同様の方法でアクセスすることもできます。

​​

含まれているCSSファイルのhref。

document.styleSheets[0].cssRules 

シート内のすべてのクラス。

これが誰かを助けることを願っています!

0

ルールを既存のスタイルシートに追加する場合、公式の方法はinsertRuleメソッドです。おそらくブラウザ上でもっと簡単になり、次にテキストを追加するだけです。また、以下のようにすると、特定のCSSルールが有効な構文でない場合は、スキップしてドキュメントの整合性を保護します。

文字列タイミングのためだけにjQueryを使用しますが、とにかく必要はありません。

スタイルタグのIDを指定する必要があります。ここでは、@AtheistP3aceさんへの答えを追加

function AddMoreStyles(code, styleTagId) { 

    var sheet = document.getElementById('#' + styleTagId); 

    let lines = code.replace(/[\r\n\t]/gm, ' ').split(/}/); 
    if (!sheet) { 
     return; 
    } 
    sheet = sheet.styleSheet || sheet.sheet || sheet; 
    lines.forEach(function (str) { 
     str = $.trim(str) + '}'; 
     let m = str.match(/(.+?)\{(.*?)}/), m1, m2; 
     if (m) { 
      m1 = $.trim(m[1]); 
      m2 = $.trim(m[2]); 
      try { 
       if (sheet.insertRule) sheet.insertRule(m1 + '{' + m2 + '}', sheet.cssRules.length); 
       else sheet.addRule(m1, m2); 
      } catch (e) { 
       console.log("!ERROR in css rule: " + e.message); 
      } 
     } 
    }); 
}; 
0

は、スタイルブロックの内容を変更するには、純粋なJavaScriptを使用して関数である。

// Change the CSS in the style section. 
// Property is the name of the class or id E.G. ".mdc-card" or "#main". 
// Style is the name of the CSS style. E.G. "Background". 
// Value is the setting that the style will use, E.G. "Red" 
// WARNING: STOPS AND EXECUTES ON THE FIRST MATCH DOES NOT PROCESS MORE AFTER THAT!!! 
function changeCSS(property, style, value, cssSectionID) { 
    if (cssSectionID === undefined) { 
     cssSectionID = "mainCSS"; 
    } 
    // Get the current CSS sheet. 
    var mainCSS = document.getElementById("mainCSS"); 
    var changeStatus = false; 
    // Refine the stylesheet into a more easily processed form. 
    // It is done here as making it part of the variable definition produces issues where you still need to call the sheet property. 
    mainCSS = mainCSS.sheet; 

    // Only execute if the user has specified values for each of the required parameters. 
    if (property !== undefined && style !== undefined && value !== undefined) { 
     // Loop through all of the CSS Properties until the specified property is found. 
     for (var index = 0; index < mainCSS.cssRules.length; index++) { 

      // Only apply the value of the property matches. 
      if (mainCSS.cssRules[index].selectorText === property.toString()) { 
       // Apply the specified property value to the. 
       mainCSS.cssRules[index].style[style.toString()] = value.toString(); 

       // Sets the exit status and breaks the loop's execution. 
       changeStatus = true; 
       break; 
      } 
     } 
    } 
    // Returns the result of the operation. True being successful and false being unsuccessful. 
    return changeStatus; 
} 
関連する問題