Create a link label with JQuery
If you like to use jquery in your development, then using jquery to create the link tag should be like this:
The code is as follows |
Copy Code |
var cssurl = '/style.css ', Linktag = $ (' <link href= ' + cssurl + ' "rel=" stylesheet "type=" Text/css "media=" ' + "(Media | | "All") + ' "charset=" ' + CharSet | | "Utf-8" + ' "/>"); See clearly that the link tag is dynamically added to the head $ ($ (' head ') [0]). Append (Linktag); |
Create a link label with native JavaScript
If you like pure natural JavaScript, you need to write this:
The code is as follows |
Copy Code |
var head = document.getElementsByTagName (' head ') [0], Cssurl = '/style.css ', Linktag = document.createelement (' link ');
linktag.id = ' Dynamic-style '; Linktag.href = Cssurl; Linktag.setattribute (' rel ', ' stylesheet '); Linktag.setattribute (' media ', ' all '); Linktag.setattribute (' type ', ' text/css ');
Head.appendchild (Linktag); |
IE Method createStyleSheet
IE createStyleSheet method is also very convenient.
The code is as follows |
Copy Code |
var head = document.getElementsByTagName (' head ') [0], Cssurl = ' Themes/bluenight/style.css ', Document.createstylesheet www.111Cn.net The link tag has been added to the head, how to say, it is very convenient Linktag = Document.createstylesheet (Cssurl); |
createStyleSheet ([sURL] [, Iindex]) method accepts two parameters, sURL is the URL path of the CSS file. Iindex is an optional parameter that refers to the index position of the inserted link in the page stylesheets collection, which defaults to adding the newly created style at the end.
a complete solution
Basically all introduced, to see the Complete solution bar:
The code is as follows |
Copy Code |
function Createlink (Cssurl,lnkid,charset,media) { var head = $ ("head") [0]), Linktag = null;
if (!cssurl) { return false; }
Linktag = $ (' <link href= ' + cssurl + ' "rel=" stylesheet "type=" Text/css "media=" ' + "(Media | | "All") + ' "charset=" ' + CharSet | | "Utf-8" + ' "/>");
Head.append (Linktag); } Function Createlink (cssurl,lnkid,charset,media) { var head = document.getElementsByTagName (' head ') [0], linktag = null; &NBSP if (!cssurl) { return false; Linktag = document.createelement (' link '); linktag.setattribute (' id ', Lnkid | | ' Dynamic-style ')); linktag.setattribute (' rel ', ' stylesheet '); linktag.setattribute (' CharSet '), (CharSet | | ' Utf-8 ')); linktag.setattribute (' Media ', (media| | ') All)); linktag.setattribute (' type ', ' text/css '); linktag.href = cssurl; head.appendchild (Linktag); &NBSP } |