我在LESS文件中创建了2个变量
@navSpritePath: '/i/data-board/navigation/navigation-sprite.gif';
@navSpritePath2x: ~`@{navSpritePath}.replace(/\.[\w\?=]+$/, function(match) { return "@2x" + match; })`;
有没有办法抽象 @ navSpritePath2x 的赋值,以便我只是传递路径来执行函数并返回字符串?
LESS有自己的数学和颜色辅助函数。我想创建自己的,所以看起来像:
@navSpritePath: '/i/data-board/navigation/navigation-sprite.gif';
@navSpritePath2x: createPath2x(@navSpritePath);
///sudo code - does not work
.createPath2x (@path){
~`@{path}.replace(/\.[\w\?=]+$/, function(match) { return "@2x" + match; })`;
}
答案 0 :(得分:4)
如果您希望能够更改将接收作业的变量名navSpritePath2x
,那么我认为LESS不可能。
但是,如果您只想将那个变量名称抽象为mixin,那么就有可能。有了这样的话,可以这样使用(例如):
<强> LESS 强>
@navSpritePathOne: '/i/data-board/navigation/navigation-sprite1.gif';
@navSpritePathTwo: '/i/data-board/navigation/navigation-sprite2.gif';
.createPath2x(@path){
@navSpritePath2x: `@{path}.replace(/\.[\w\?=]+$/, function(match) { return "@2x" + match; })`;
}
.test {
background-image: url(@navSpritePathOne);
.high-density & {
.createPath2x(@navSpritePathOne);
background-image: url(@navSpritePath2x);
}
}
.test2 {
background-image: url(@navSpritePathTwo);
.high-density & {
.createPath2x(@navSpritePathTwo);
background-image: url(@navSpritePath2x);
}
}
CSS输出
.test {
background-image: url('/i/data-board/navigation/navigation-sprite1.gif');
}
.high-density .test {
background-image: url("/i/data-board/navigation/navigation-sprite1@2x.gif");
}
.test2 {
background-image: url('/i/data-board/navigation/navigation-sprite2.gif');
}
.high-density .test2 {
background-image: url("/i/data-board/navigation/navigation-sprite2@2x.gif");
}
当然,如果你总是要用它来设置一组类似的属性(比如说,与background-image
相关),那么你可以将它全部放入mixin中,这样你就不会必须重复代码:
少 少
@navSpritePathOne: '/i/data-board/navigation/navigation-sprite1.gif';
@navSpritePathTwo: '/i/data-board/navigation/navigation-sprite2.gif';
.createPath2x(@path){
background-image: url(@path);
.high-density & {
background-image: `@{path}.replace(/\.[\w\?=]+$/, function(match) { return "@2x" + match; })`;
}
}
.test {
.createPath2x(@navSpritePathOne);
}
.test2 {
.createPath2x(@navSpritePathTwo);
}
CSS输出与上面显示的LESS代码更长相同。
答案 1 :(得分:0)
我知道这并没有直接回答你的问题,但我想分享一下我在自己的项目中如何完成你想要做的事情。我将所有高密度图像存储在具有相同名称的/ 2x文件夹中。确保更改背景尺寸尺寸以匹配您的图像。
我希望这会有所帮助。
//Variables
@highdensity: ~"only screen and (-webkit-min-device-pixel-ratio: 1.5)",
~"only screen and (min--moz-device-pixel-ratio: 1.5)",
~"only screen and (-o-min-device-pixel-ratio: 3/2)",
~"only screen and (min-device-pixel-ratio: 1.5)";
@CDNURL: "cdn.mydomain.com/assets/";
@CDNURL-Retina: "@{CDNURL}2x/";
//Background image URL Function
.BGImage-HD(@image) {
background-image: url('http://@{CDNURL}@{image}');
@media @highdensity {
background-image: url('http://@{CDNURL-Retina}@{image}');
}
}
//Usage
.navSprite {
.BGImage-HD("navigation-sprite.gif");
@media @highdensity {
.background-size(360px, 240px);
}
}