Home  >  Article  >  Web Front-end  >  javascript 动态加载 css 方法总结_javascript技巧

javascript 动态加载 css 方法总结_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:50:10970browse
1. 用在外部CSS文件中加载必须的文件
@importurl(style.css);
//只能用在CSS文件中或者style标签中
2. 简单的在页面中加载一个外部CSS文件
document.createStyleSheet(cssFile);
2. 用createElement方法创建CSS的Link标签
varhead=document.getElementsByTagName('HEAD').item(0);
varstyle=document.createElement('link');
style.href='style.css';
style.rel='stylesheet';
style.type='text/css';
head.appendChild(style);
下面是经常会用到的两个函数.
复制代码 代码如下:

functionloadJs(file){
  varscriptTag=document.getElementById('loadScript');
  varhead=document.getElementsByTagName('head').item(0);
  if(scriptTag)head.removeChild(scriptTag);
  script=document.createElement('script');
  script.src="../js/mi_"+file+".js";
  script.type='text/javascript';
  script.id='loadScript';
  head.appendChild(script);
}
functionloadCss(file){
  varcssTag=document.getElementById('loadCss');
  varhead=document.getElementsByTagName('head').item(0);
  if(cssTag)head.removeChild(cssTag);
  css=document.createElement('link');
  css.href="../css/mi_"+file+".css";
  css.rel='stylesheet';
  css.type='text/css';
  css.id='loadCss';
  head.appendChild(css);
}
Statement:
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