在此期间question我想调用一些较少的函数,例如在javascript中变暗,变亮和旋转。我在node.js中这样做了它的工作原理:
#!/usr/bin/env node
var less = require('less');
var args = process.argv.slice(2);
less.render(".my{ color:lighten("+ args[0]+","+args[1]+"%); }", function (e, css) {
console.log(css.match(/\#[0-9a-fA-F]+/)[0]);
});
这是输出:
$ ./my "#000" 13.5
#222222
但是我在html和less.js文件中使用了question中的解决方案并且做了这个:
<html>
<head>
<title></title>
<script language="JavaScript" src="less-1.7.0.min.js"></script>
<script language="JavaScript">
var lessColor = {
/*
|--------------------------------------------------------------------------
| Lighten
|--------------------------------------------------------------------------
*/
lighten: function (col, val) {
col = col.replace(/#/g, ''); //Remove the hash
var color = new less.tree.Color(col); //Create a new color object
var amount = new less.tree.Value(val); //Create a new amount object
var newRGB = less.tree.functions.lighten(color, amount); //Get the new color
var hex = (newRGB.rgb[0] + 256 * newRGB.rgb[1] + 65536 * newRGB.rgb[2]).toString(16);
hex = hex.split('.', 1); //Remove everything after the decimal if it exists
//Add padding to the hex to make it 6 characters
while (hex.length < 6) {
hex = hex + '0';
}
hex = '#' + hex; //Add the hash
return hex; //return the color
}
};
console.log(lessColor.lighten("#000",13.5));
</script>
</head>
<body>
</body>
</html>
但控制台中的输出不同:
我很确定#222222是正确的结果,但我怎样才能在javascript中获得此结果?
答案 0 :(得分:1)
从评论中可以看出,以下代码将为您提供#222222
:
var lessColor = {
lighten: function (color, amount) {
color = new (less.tree.Color)(color.substring(1));
amount = new(less.tree.Dimension)(amount, '%');
return less.tree.functions.lighten(color, amount).toRGB();
}
};
console.log(lessColor.lighten('#000',13.5));
请注意color.substring(1)
就像col.replace(/#/g, '');
一样删除了起始#
。 less.tree.Color的输入是十六进制颜色三元组,较少解析器使用以下代码进行该转换:
var rgb;
if (parserInput.currentChar() === '#' && (rgb = parserInput.$re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) {
var colorCandidateString = rgb.input.match(/^#([\w]+).*/); // strip colons, brackets, whitespaces and other characters that should not definitely be part of color string
colorCandidateString = colorCandidateString[1];
if (!colorCandidateString.match(/^[A-Fa-f0-9]+$/)) { // verify if candidate consists only of allowed HEX characters
error("Invalid HEX color code");
}
return new(tree.Color)(rgb[1]);
}
答案 1 :(得分:0)
纠正@Bass Jobsen的回答 https://stackoverflow.com/a/26811314/3027390
在Less的现代版本中,不再有<label for="event_categories">Categories</span></label>
^^^^^^^
。
您应该使用less.tree.functions.lighten
代替。
这适用于任何其他Less函数(不仅仅是颜色)。
因此,更新的答案应如下所示:
less.functions.functionRegistry.get('lighten')