JavaScript_javascript 기술에 CSS를 동적으로 삽입하는 방법

WBOY
풀어 주다: 2016-05-16 15:26:17
원래의
1668명이 탐색했습니다.

구성 요소를 작성할 때 구성 요소 기능과 관련된 일부 CSS 스타일을 JS에 캡슐화하여 더 응집력 있고 쉽게 변경할 수 있도록 하고 싶을 때가 있습니다. JS는 두 단계로 CSS를 동적으로 삽입합니다. 1. 스타일 개체
를 만듭니다. 2. 스타일 시트의 insertRule 또는 addRule 메소드를 사용하여 스타일을 추가하세요

1. 스타일시트 보기

document.styleSheets를 먼저 보고 마음대로 페이지를 엽니다

처음 세 개는 링크 태그를 통해 소개된 CSS 파일이고, 네 번째는 스타일 태그를 통해 페이지에 인라인된 CSS입니다. 다음과 같은 속성을 갖습니다

각 cssRule에는 다음 속성이 있습니다.

cssText는 바로 스타일로 작성된 소스코드입니다.

2. CSS를 동적으로 삽입합니다
먼저 스타일 개체를 생성하고 해당 스타일시트 개체를 반환해야 합니다

/*
 * 创建一个 style, 返回其 stylesheet 对象
 * 注意:IE6/7/8中使用 style.stylesheet,其它浏览器 style.sheet
 */
function createStyleSheet() {
 var head = document.head || document.getElementsByTagName('head')[0];
 var style = document.createElement('style');
 style.type = 'text/css';
 head.appendChild(style);
 return style.sheet ||style.styleSheet;
}
로그인 후 복사

다음과 같이 addCssRule 함수를 추가하세요

/*
 * 动态添加 CSS 样式
 * @param selector {string} 选择器
 * @param rules {string} CSS样式规则
 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的
 */
function addCssRule(selector, rules, index) {
 index = index || 0;
 if (sheet.insertRule) { 
  sheet.insertRule(selector + "{" + rules + "}", index); 
 } else if (sheet.addRule) { 
  sheet.addRule(selector, rules, index); 
 }
}
로그인 후 복사

표준 브라우저는 insertRule을 지원하고, IE의 하위 버전은 addRule을 지원한다는 점에 유의하세요.
전체 코드는 다음과 같습니다

/*
 * 动态添加 CSS 样式
 * @param selector {string} 选择器
 * @param rules {string} CSS样式规则
 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的
 */
var addCssRule = function() {
 // 创建一个 style, 返回其 stylesheet 对象
 // 注意:IE6/7/8中使用 style.stylesheet,其它浏览器 style.sheet
 function createStyleSheet() {
  var head = document.head || document.getElementsByTagName('head')[0];
  var style = document.createElement('style');
  style.type = 'text/css';
  head.appendChild(style);
  return style.sheet ||style.styleSheet;
 }
 
 // 创建 stylesheet 对象
 var sheet = createStyleSheet();
 
 // 返回接口函数
 return function(selector, rules, index) {
  index = index || 0;
  if (sheet.insertRule) { 
   sheet.insertRule(selector + "{" + rules + "}", index); 
  } else if (sheet.addRule) { 
   sheet.addRule(selector, rules, index); 
  }
 }
}();
로그인 후 복사


모바일 단말기나 최신 브라우저만 지원하는 경우에는 IE 하위 버전에서 판단한 코드를 제거할 수 있습니다

/*
 * 动态添加 CSS 样式
 * @param selector {string} 选择器
 * @param rules {string} CSS样式规则
 * @param index {number} 插入规则的位置, 靠后的规则会覆盖靠前的,默认在后面插入
 */
var addCssRule = function() {
 // 创建一个 style, 返回其 stylesheet 对象
 function createStyleSheet() {
  var style = document.createElement('style');
  style.type = 'text/css';
  document.head.appendChild(style);
  return style.sheet;
 }
 
 // 创建 stylesheet 对象
 var sheet = createStyleSheet();
 
 // 返回接口函数
 return function(selector, rules, index) {
  index = index || 0;
  sheet.insertRule(selector + "{" + rules + "}", index);
 }
}();
로그인 후 복사

위 내용은 JavaScript에 CSS를 동적으로 삽입하는 방법입니다. 모든 분들의 학습에 도움이 되었으면 좋겠습니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!