JavaScript access modify CSS style sheet

Source: Internet
Author: User

JavaScript access to modify the style sheet, you can easily modify the page dynamically:

A CSS style that accesses the style property in an element

This can be accessed directly using the style object, for example:

<div id = "MDiv" >....</div>

The way to access CSS is:

<script type= "Text/javascript" >

Get elements

var odiv = Document.getelementyid ("MDiv");

Access the element's style object, access the properties in the object, or modify the value of the property to assign it directly to him

alert (ODiv.style.backgroundColor);

</script>

II. accessing externally defined CSS styles (class-defined CSS styles)

This cannot be accessed using the method above, because the CSS data is not stored in the Style property, it is stored in the class.

Access method: First obtain a reference to the style sheet that defines the class, This is done with the Document.stylesheets collection, which contains all the stylesheets in the HTML page, and the DOM defines a collection of cssrules for each style sheet that contains the CSS rules defined in the style sheet (note: Mozilla and Safasi are CSSR Ules, and IE Chinese rules).

For example:

<style>

/* First Rule */

div.ss{

background-color:red;

width:101px;

}

/* Rule number two */

a.btn2{

Background:url (imag/2-accessctl.jpg);

}

</style>

Access CSS:

var ocssrules = document.stylesheets[0].cssrules| | Document.stylesheets[0].rules;

Access to the first rule

alert (Ocssrules[0].style.backgroundcolor);

Setting the value

Ocssrules[0].style.width = "992px";

Access to the second rule

alert (Ocssrules[1].style.background);

Setting the value

ocssrules[0].style.background = "url (imag/3-back.jpg);";

These are some of the simple applications that I have used, and the specific in-depth use of the DOM technology section of the JavaScript advanced programming

Source: http://echoetang.iteye.com/blog/525916

JavaScript access modify CSS style sheet

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.