23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 8 ■ SCRIPTING CSS<br />

330<br />

• The numeric index of the new rule. We have that number on hand in the index, so<br />

just pass that in, and we’re done.<br />

Now let’s code a path for Internet Explorer to run. Its method, addRule(), takes three parameters:<br />

the text for the selector, the text for the declarations, and the numeric index for where to insert the rule.<br />

Simply pass in the values of selector, declarations, and index. It’s simple as can be:<br />

function insertRule(element, selector, declarations, index) {<br />

var sheet = element.sheet || element.styleSheet;<br />

var rules = sheet.cssRules || sheet.rules;<br />

if (typeof index === "string") {<br />

index = findIndex(element, index);<br />

}<br />

if (typeof index !== "number") {<br />

index = rules.length;<br />

}<br />

if (sheet.insertRule) {<br />

sheet.insertRule(selector + "{" + declarations + "}", index);<br />

} else if (sheet.addRule) {<br />

sheet.addRule(selector, declarations, index);<br />

}<br />

}<br />

Between the rules with the selectors "ul.blue a" and "ul.fuchsia a", let’s insert a new one to swap<br />

the sprite from blue to fuchsia by calling insertRule() like so. Verify your work with Figure 8–11.<br />

function insertRule(element, selector, declarations, index) {<br />

var sheet = element.sheet || element.styleSheet;<br />

var rules = sheet.cssRules || sheet.rules;<br />

if (typeof index === "string") {<br />

index = findIndex(element, index);<br />

}<br />

if (typeof index !== "number") {<br />

index = rules.length;<br />

}<br />

if (sheet.insertRule) {<br />

sheet.insertRule(selector + "{" + declarations + "}", index);<br />

} else if (sheet.addRule) {<br />

sheet.addRule(selector, declarations, index);<br />

}<br />

}<br />

insertRule(document.getElementById("spriteStyles"), "ul.blue a",<br />

"background-image:url(images/fuchsia.gif)", "ul.fuchsia a");

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!