国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

動態樣式類封裝JS代碼

2024-05-06 14:14:11
字體:
來源:轉載
供稿:網友
文件名StyleSheet.js
代碼如下:
// CssRule類由StyleSheet.getRule方法返回,不直接創建
function CssRule(rule) {
this.rule = rule;
this.style = rule.style;
this.selectorText = rule.selectorText;
this.index = null;
}
function StyleSheet() {
var head = document.getElementsByTagName("head")[0];
//通過新建標簽來創建新樣式
/*
在此不用document.createStyleSheet來完成,是因為在FF下
如果未導入任何CSS文件的情況下document.createStyleSheet方法失敗
*/
var style = document.createElement("style");
style.type = "text/css";
head.appendChild(style);
this.CatchStyle(document.styleSheets.length - 1);
}
StyleSheet.prototype = {
//可直接捕獲現有Style
CatchStyle: function(index) {
this.style = document.styleSheets[index];
if (navigator.userAgent.indexOf("MSIE") < 0) { //非IE瀏覽器補丁
this.style.addRule = function(selector, style) {
var index = this.cssRules.length;
this.insertRule(selector + "{" + style + "}", index);
};
this.style.removeRule = function(index) {
this.deleteRule(index);
};
}
},
//新增樣式
AddRule: function(selector, style) {
this.style.addRule(selector, style);
},
//刪除樣式
RemoveRule: function(index) {
this.style.removeRule(index);
},
//取得所有樣式
getRules: function() {
if (this.style.rules) { //IE
return this.style.rules;
}
return this.style.cssRules; //非IE
},
//通過選擇器,取得樣式
getRule: function(selector) {
var rules = this.getRules();
for (var i = 0; i < rules.length; i++) {
var r = rules[i];
if (r.selectorText == selector) {
var rule = new CssRule(r);
rule.index = i;
return rule;
}
}
return null;
}
};

調用示例代碼
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="StyleSheet.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript"><!--
var ss = new StyleSheet();
window.onload = function() {
ss.AddRule(".test", "color:#FF0000; background-color:#F0F0F0; font-size:12px; border:solid 1px #A0A0A0;");
}
function Set() {
var r = ss.getRule(".test");
var slt = document.getElementById("tbSelector").value;
var v = document.getElementById("tbValue").value;
var style = r.style;
style[slt] = v;
}
// --></script>
</head>
<body>
樣式<input id="tbSelector" type="text" value="width" />
值<input id="tbValue" type="text" value="300px" />
<input type="button" value="設置" onclick="Set()" />
<div class="test">a</div>
<div class="test">b</div>
<div class="test">c</div>
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 玛曲县| 崇左市| 会宁县| 武川县| 甘孜县| 锡林郭勒盟| 游戏| 威海市| 永兴县| 苏尼特左旗| 揭东县| 陵水| 馆陶县| 南丰县| 玉环县| 鹤岗市| 道真| 沂源县| 平舆县| 阿拉善左旗| 天津市| 普格县| 怀柔区| 凤阳县| 景泰县| 浮山县| 墨脱县| 天祝| 环江| 腾冲县| 吉木萨尔县| 万州区| 金乡县| 岚皋县| 绥化市| 霍城县| 桦南县| 美姑县| 年辖:市辖区| 蚌埠市| 洞头县|