How to create or add CSS style sheets dynamically using JavaScript _javascript tips

Source: Internet
Author: User

1, the simple method, regardless, directly this can be:

Document.createstylesheet (). Csstext = ' tag {color:red; ' +
    //This comment only helps to understand in current JS and will not be written in CSS
    ' width:300px;height : 150px} ' +
    '. Class name {...} ' +
    ' #ID们 {...} '
;

Finish the job. I like the semicolon to write, and it's better to align it with the beginning of the instruction, especially when there are other statements behind it.

2, a better way to prevent repeated additions, you can add a Stylesheet ID and judge it to achieve:

if (!document.stylesheets[' to create a style sheet ID such as Theforever ']) {//first check to see if the style sheet ID you want to establish exists to prevent the repeated addition of the
 var ss = Document.createstylesheet ();
 Ss.owningElement.id = ' to be established style sheet ID such as Theforever ';
 Ss.csstext = ' Tag {display:inline-block;overflow:hidden ' +
  //This annotation only helps understand in current JS, and will not be written into CSS
  ' text-align:left; width:300px;height:150px} ' +
  '. Class name {...} ' +
  ' #ID们 {...} '
 ;
 }

The above article with JavaScript dynamic build or add CSS style sheet implementation method is small set to share all the content, hope to give you a reference, also hope that we support cloud habitat community.

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.