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

How to introduce css in js

藏色散人
Release: 2023-01-05 16:09:35
Original
8222 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template