Home >Web Front-end >JS Tutorial >How to introduce css in js

How to introduce css in js

藏色散人
藏色散人Original
2021-04-19 09:51:258231browse

How to introduce css into js: 1. Use the "document.write" method to output the link tag that introduces css; 2. Use the createElement method to dynamically create a link tag to introduce css.

How to introduce css in js

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

js imports css files

1. Use the document.write method to output the link tag that imports css

Add the following example code at the top of the calling file

<script>
    document.write(&#39;<link rel="stylesheet" href="main.css">&#39;);
</script>

2. Use the createElement method to dynamically create link tags to introduce css

Put the following code into the Body

<script>
    new_element = document.createElement(&#39;link&#39;);
    new_element.setAttribute(&#39;rel&#39;, &#39;stylesheet&#39;);
    new_element.setAttribute(&#39;href&#39;, &#39;main.css&#39;);
    document.body.appendChild(new_element);
</script>

Let’s analyze the key lines of code :

First we use document.createElement('link') to generate a link tag;

Then set its rel attribute to stylesheet and href to main.css;

Finally, this tag is dynamically added to the body.

【Recommended learning: javascript advanced tutorial

The above is the detailed content of How to introduce css in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn