Oto niewielka korekta odpowiedzi przez vsync.
function addRule(stylesheetId, selector, rule) {
var stylesheet = document.getElementById(stylesheetId);
if (stylesheet) {
stylesheet = stylesheet.sheet;
if (stylesheet.addRule) {
stylesheet.addRule(selector, rule);
} else if (stylesheet.insertRule) {
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}
}
}
Po uzyskaniu obiektu DOM przez document.getElementById można użyć „arkusz” właściwość, aby uzyskać dostęp do rzeczywistej arkusza stylów. Dlatego upewnij się, że podałeś identyfikator arkusza stylów, który chcesz zmienić. Nawet jeśli jest to zewnętrzny plik CSS, wystarczy podać identyfikator.
A oto moja strona testowa
<!DOCTYPE html>
<html>
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script>
var
index = 0,
items = [
{ selector: "h1", rules: "color:#3333BB;font: bold 18px Tahoma;padding: 12px 0 0 0;" },
{ selector: "p", rules: "padding:0;margin:0;background-color:#123456;color:#ABCDEF;"},
{ selector: "b", rules: "font-weight:normal;"},
{ selector: "i", rules: "color:#66FF66;" }
];
function addRule(stylesheetId, selector, rule) {
var stylesheet = document.getElementById(stylesheetId);
if (stylesheet) {
stylesheet = stylesheet.sheet;
if (stylesheet.addRule) {
stylesheet.addRule(selector, rule);
} else if (stylesheet.insertRule) {
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}
}
}
$(document).ready(function() {
$("button").click(function() {
addRule("myStyles", items[index].selector, items[index].rules);
index++;
});
});
</script>
<style id="myStyles">
div
{
border: solid 1px black;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<button>Click Me</button>
<div>
<h1>test</h1>
<p>Paragraph One</p>
<p>Paragraph with <b>bold</b> and <i>Italics</i></p>
<p>Paragraph 3</p>
</div>
</body>
</html>
Poprosiłem ten questio, n ale już myśli o sposób aby go rozwiązać. Chciałem podzielić się tym rozwiązaniem ze społecznością stackoverflow, która może potrzebować tego. – vsync