I believe that many front-end friends have encountered the need to use JavaScript to dynamically create style sheet tags-link tags. Here we will talk about how to dynamically create link tags in the browser.
Use jQuery to create link tags
If you like to use jQuery in development, then using jQuery to create link tags should look like this:
var cssURL = '/style.css', linkTag = $('<link href="' + cssURL + '" rel="stylesheet" type="text/css" media="' + (media || "all") + '" charset="'+ charset || "utf-8" +'" />'); // 请看清楚,是动态将link标签添加到head里 $($('head')[0]).append(linkTag);
Use native JavaScript to create link tags
If you like pure natural JavaScript, you need to write like this:
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);
Special method in IE createStyleSheet
The createStyleSheet method unique to IE is also very convenient.
var head = document.getElementsByTagName('head')[0], cssURL = 'themes/BlueNight/style.css', // document.createStyleSheet 的同时就已经把link标签添加到了head中了,怎么讲呢,倒是挺方便 linkTag = document.createStyleSheet(cssURL);
The createStyleSheet([sURL] [, iIndex]) method accepts two parameters, sURL is the URL path of the CSS file. iIndex is an optional parameter, which refers to the index position of the inserted link in the stylesheets collection on the page. The default is to add the newly created style at the end.
Basically the introduction is over, let’s take a look at the complete solution:
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; 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); }
The above is the detailed content of Detailed explanation of usage examples for creating link tags using js and jquery. For more information, please follow other related articles on the PHP Chinese website!