时间:2021-07-01 10:21:17 帮助过:14人阅读
使用 jQuery 创建 link 标签
如果你开发中喜欢用jQuery,那么用jQuery在创建link标签应该是这样的:
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);使用原生 JavaScript 创建 link 标签
如果你喜欢纯天然的 JavaScript,就要需要这么写:
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 里特有的方法 createStyleSheet
IE 里特有的方法 createStyleSheet 方法也是很方便。
var head = document.getElementsByTagName('head')[0],
cssURL = 'themes/BlueNight/style.css',
// document.createStyleSheet 的同时就已经把link标签添加到了head中了,怎么讲呢,倒是挺方便
linkTag = document.createStyleSheet(cssURL);
createStyleSheet( [sURL] [, iIndex])方法接受两个参数,sURL就是CSS文件的URL路径。iIndex 为可选参数,指插入的link在页面中stylesheets collection的索引位置,默认是在最后添加新创建的样式。
基本上都介绍完了,来看看完整的解决方案吧:
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);
}以上就是使用js和jquery创建link标签用法实例详解的详细内容,更多请关注Gxl网其它相关文章!