CSS files are used to describe how HTML elements are displayed. There are various ways to add CSS files to HTML documents. JavaScript can load CSS files in HTML documents, so how to use JavaScript to load CSS files? The following article will introduce it to you, I hope it will be helpful to you. [Video tutorial recommendation: JavaScript tutorial]
##How to do:
● Get the HTML header element using the document.getElementsByTagName() method. ● Use the createElement('link') method to create a new link element. ●Initialize the attributes of the link element. ●Append the link element to the header.Code Example
The following is a code example to see how JavaScript loads CSS files in HTML documents.Example 1:
Create a file named style.css:.demo { width: 400px; height: 200px; border: 1px solid red; color:red; margin: 50px auto; text-align: center; line-height: 200px; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> Load CSS file using JavaScript </title> <script> // 获取HTML头元素 var head = document.getElementsByTagName('head')[0]; // 创建新链接元素 var link = document.createElement('link'); // 设置链接元素的属性 link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // 将链接元素附加到HTML头 head.appendChild(link); </script> </head> <body> <h2 class="demo">php中文网!</h2> </body> </html>
Example 2:
style.css file code:.demo { width: 400px; height: 100px; border: 1px solid green; font-size:25px; font-weight:bold; color:white; background-color:pink; text-align:center; line-height: 100px; margin: 50px auto; }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> Load CSS file using JavaScript </title> <script> // 创建新链接元素 var link = document.createElement('link'); // 设置链接元素的属性 link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // 获取 head元素以向其追加链接元素 document.getElementsByTagName('head')[0].appendChild(link); </script> </head> <body> <h2 class="demo">php中文网!</h2> </body> </html>
The above is the detailed content of How to load CSS files using JavaScript? (code example). For more information, please follow other related articles on the PHP Chinese website!