JavaScript access modify CSS style sheet

Source: Internet
Author: User

1. Accessing the CSS style of the style property in the element

You can use the DOM operation to directly access the internal CSS style based on the ID of the property or the name tag, directly using the style object to access

<div id= "myID" style= "Backgroundcolor:blue;" ></div>

<script type= "Text/javascript" >

var Mydiv1=document.getelementbyid ("myID");

alert (Mydiv1.style.backgroundColor);

</script>

2. Accessing externally defined CSS styles

External CSS is stored in the class, not stored in the Style property, we need to use the style sheet of the class. We first get a reference to the stylesheet that defines the class, which is implemented with the Document.stylesheets collection , which contains all the styles in the HTML page, and the DOM defines a collection of Cssrules for each style sheet. This collection contains the CSS rules that are defined in the style sheet (ie is used in rules).

CSS style sheet:

First Rule

div{

Background-color:blue;

width:200px;

height:200px;

}

Rule number Two

a.btn1{

Background:url (imag/1.jpg);

}

accessing CSS

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

Access to the first rule

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

Setting the value

Mycssrules[0].style.backgroundcolor= "BLACK";

Access to the second rule

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

Setting the value

mycssrules[1].style.background= "url (imag/2.jpg)";

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.