元素的样式
示例代码
获取元素的样式
var backgroundColor = domlib.css(node,"backgroundColor");
设置元素的样式
domlib.css(node,"backgroundColor","red");
工具函数列表
uDOMlib所提供的工具函数之中,有一部分与元素样式相关,下面列出部分函数的源代码实现以供参考。
addClass
給元素添加一个或多个类。 该方法不会移除已存在的class属性,仅仅添加一个或多个class属性,添加多个类需使用空格分隔类名。
addClass: function(el,name){
var re = classRE(name);
if (!el.className.match(re)){
el.className += (el.className ? " " : "") + name;
}
}
css
获取或设置元素的一个或多个样式属性
css: function(el,property, value){
if (arguments.length < 3) {
var computedStyle,
computedStyle = getComputedStyle(el, '')
if (utils.isString(property)) {
return el.style[utils.camelize(property)] || computedStyle.getPropertyValue(property)
} else if (utils.isArray(property)) {
var props = {};
Array.forEach(property, function(prop){
props[prop] = (el.style[String.camelize(prop)] || computedStyle.getPropertyValue(prop))
});
return props
}
}
var css = '' ;
if (type(property) == 'string') {
if (!value && value !== 0)
el.style.removeProperty(dasherize(property));
else
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
for (key in property)
if (!property[key] && property[key] !== 0)
el.style.removeProperty(dasherize(key));
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
}
el.style.cssText += ';' + css;
return this;
}
hasClass
检查元素是否包含指定的类。
hasClass: function(el,name){
var re = classRE(name);
return el.className.match(re);
}
removeClass
从元素移除一个或多个类
removeClass: function(el,name){
var re = classRE(name);
if (el.className.match(re)){
el.className = el.className.replace(re, " ");
}
return this;
}
toggleClass
对元素的一个或多个类进行切换。 该方法检查元素是否已设置指定的类。如果不存在则添加类,如果已设置则删除之。
toggleClass: function(el,name){
var re = classRE(name);
if (el.className.match(re)){
el.className = el.className.replace(re, " ");
} else {
el.className += (el.className ? " " : "") + name;
}
return this;
}