[英]Convert CSS rule to JavaScript property
Is there a quick way or predefined JavaScript method that converts 有没有一种快速的方法或预定义的JavaScript方法可以转换
"text-align"
"-webkit-transform"
"position"
"background-image"
into 进入
"textAlign"
"webkitTransform"
"position"
"backgroundImage"
with vanilla javascript (no jQuery, ect)? 与香草的JavaScript(没有jQuery的,等等)?
Use this regex replace: 使用此正则表达式替换:
"text-align".replace(/-([a-z])/g,function(m,l,i){return i?l.toUpperCase():l})
It matches a hyphen and then a letter. 它与连字符和字母匹配。 The replace returns the letter, capitalized if the index is truthy (not 0).
替换返回字母,如果索引为真(不为0),则大写。
After hunting around I found that the variable I was dealing with was of type CSSStyleDeclaration
which comes with a method getPropertyCSSValue 搜寻之后,我发现我要处理的变量是
CSSStyleDeclaration
类型,该类型带有方法getPropertyCSSValue
Simplified extract 简化提取
var rules = document.styleSheets[0/*sheetIndex*/].rules[0/*ruleIndex*/];
console.log(rules.toString()); // "[object CSSStyleRule]"
for(var a = 0; a<rules.style.length; a++)
{
var rule = rules.style[a];
console.log(rule,rules.style.getPropertyCSSValue(rule).cssText); // eg: "text-align","center"
}
This avoids issues with "border"
and "border-left"
这样可以避免出现
"border"
和"border-left"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.