我需要将CSS字体速记格式解析为单独的组件(font-family,font-size,font-weight,...)。这种速记格式看起来很复杂。以下是两个例子:
10px sans-serif
bold italic small-caps 1em/1.5em verdana,sans-serif
在我开始为它编写解析器之前,我可以使用已经存在的解析器吗(最好用JavaScript编写)?
答案 0 :(得分:11)
这是一个“临时DOM元素并使用jquery的css()函数”解决方案:
http://jsfiddle.net/thirtydot/tpSsE/2/
var $test = $('<span />');
$test.css('font', 'bold italic small-caps 1em/1.5em verdana,sans-serif');
alert($test.css('fontWeight'));
alert($test.css('fontStyle'));
alert($test.css('fontVariant'));
alert($test.css('fontSize'));
alert($test.css('lineHeight'));
alert($test.css('fontFamily'));
答案 1 :(得分:6)
这是我刚刚创建的字体解析器函数的简单尝试。但我不确定它是否适用于字体短手格式的所有专业。
function parseFont(font)
{
var fontFamily = null,
fontSize = null,
fontStyle = "normal",
fontWeight = "normal",
fontVariant = "normal",
lineHeight = "normal";
var elements = font.split(/\s+/);
outer: while (element = elements.shift())
{
switch (element)
{
case "normal":
break;
case "italic":
case "oblique":
fontStyle = element;
break;
case "small-caps":
fontVariant = element;
break;
case "bold":
case "bolder":
case "lighter":
case "100":
case "200":
case "300":
case "400":
case "500":
case "600":
case "700":
case "800":
case "900":
fontWeight = element;
break;
default:
if (!fontSize)
{
var parts = element.split("/");
fontSize = parts[0];
if (parts.length > 1) lineHeight = parts[1];
break;
}
fontFamily = element;
if (elements.length)
fontFamily += " " + elements.join(" ");
break outer;
}
}
return {
"fontStyle": fontStyle,
"fontVariant": fontVariant,
"fontWeight": fontWeight,
"fontSize": fontSize,
"lineHeight": lineHeight,
"fontFamily": fontFamily
}
}
答案 2 :(得分:4)
纯自由范围Javascript版本:
var parsedStyleForCSS = function(cssString){
var el = document.createElement("span");
el.setAttribute("style", cssString);
return el.style; // CSSStyleDeclaration object
};
var parsedStyle = parsedStyleForCSS("font: bold italic small-caps 1em/1.5em verdana,sans-serif");
console.log(parsedStyle["fontWeight"]); // bold
console.log(parsedStyle["fontStyle"]); // italic
console.log(parsedStyle["fontVariant"]); // small-caps
console.log(parsedStyle["fontSize"]); // 1em
console.log(parsedStyle["lineHeight"]); // 1.5em
console.log(parsedStyle["fontFamily"]); // verdana, sans-serif
如果您希望使用完整样式表执行类似操作,请参阅以下答案:Parsing CSS in JavaScript / jQuery
答案 3 :(得分:3)