2015-02-09——js笔记
示例1:
增加样式表
示例代码:
function addStylesheet(url, media) {
var link = document.createElement(‘link‘);
link.setAttribute(‘rel‘, ‘stylesheet‘);
link.setAttribute(‘type‘, ‘text/css‘);
link.setAttribute(‘meida‘, media);
link.setAttribute(‘href‘, url);
document.getElementsByTagName(‘head‘)[0].appendChild(link);
}
示例2:
获取样式表
示例代码:
function getStylesheet(url, media) {
var sheets = [];
for (var i = 0; i < document.styleSheets.length; i++) {
if (url && document.styleSheets[i].indexOf(url) === -1 ) {
continue;
}
if (media) {
var sheetMedia;
if (document.styleSheets[i].media.mediaText) {
sheetMedia = document.styleSheets[i].media.mediaText;
} else {
sheetMedia = document.styleSheets[i].media;
}
if (media !== sheetMedia) {
continue;
}
}
sheets.push(document.styleSheets[i]);
}
}
示例3:
删除样式表
示例代码:
function removeStylesheet(url, media) {
var sheets = getStylesheet(url, media);
for (var i = 0; i < sheets.length; i++) {
var node = sheets[i].ownerNode || sheets[i].owningElement;
sheets[i].disabled = true;
node.parentNode.removeChild(node);
}
}
示例4:
增加一条CSS规则
示例代码:
function addCssRule(selector, styles, index, url, meida) {
var declaration = ‘‘;
for (property in styles) {
if (!styles.hasOwnProperty(property)) {
continue;
}
declaration += property + ‘:‘ + styles[property] + ‘;‘;
}
var styleSheets = (typeof url === ‘array‘) ? url : getStylesheet(url, media);
var newIndex;
for (var i = 0; i < styleSheets.length; i++) {
if (styleSheets[i].insertRule) {//DOM2
newIndex = index > 0 ? index : styleSheets[i].cssRules;
styleSheets[i].insertRule(selector + ‘{‘ + declaration + ‘}‘, newIndex);
} else if (styleSheets[i].addRule) {//MSIE
newIndex = index >= 0 ? index : -1;
styleSheets[i].addRule(selector, declaration, newIndex);
}
}
}
示例5:
编辑一条css规则
示例代码:
function editCssRule(selector, styles, url, media) {
var styleSheets = (typeof url === ‘array‘) ? url : getStylesheet(url, media);
for (var i = 0; i < styleSheets.length; i++) {
var rules = styleSheets[i].cssRules || styleSheets[i].rules;
selector = selector.toUpperCase();
for (var j = 0; j < rules.length; j++) {
if (rules[j].selectorText.toUpperCase() === selector ) {
for (property in styles) {
if (!styles.hasOwnProperty(property)) {
continue;
}
rules[j].style[camelize(property)] = styles[property];
}
}
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。