2

我有一个用于视网膜背景图像的简单 LESS 样式表,但最终发生的是将我的域名添加到 url 并且无法显示图像。

例如:它会将 url 更改为http://mydomain.com/'_img/background@2x.jpg',然后它不会显示,因为它有 ' 在那里。我怎样才能防止它这样做?

.at2x(@path, @w: auto, @h: auto) {
    background-image: url(@path);
    @at2x_path: ~`"@{path}".split('.').slice(0, "@{path}".split('.').length - 1).join(".") +     "@2x" + "." + "@{path}".split('.')["@{path}".split('.').length - 1]`;

    @media all and (-webkit-min-device-pixel-ratio : 1.5) {
        background-image: url("at2x_path);
        background-size: @w @h;
    }
}

html {
    .at2x('_img/background.jpg', 1440px, 900px);
}
4

1 回答 1

4

I believe there is a typo in the code you posted ... I believe in the second background-image line the " should be an @.

Anyway, he way you could fix your problem is by doing it like this (without the quotes around @{path} in the javascript part) and then using string interpolation '@{at2x_path}' to get quotes around the output url.

in LESS:

.at2x(@path, @w: auto, @h: auto) {
    background-image: url(@path);
    @at2x_path: ~`@{path}.split('.').slice(0, @{path}.split('.').length - 1).join('.') +  '@2x.' + @{path}.split('.')[@{path}.split('.').length - 1]`;

    @media all and (-webkit-min-device-pixel-ratio : 1.5) {
        background-image: url('@{at2x_path}');
        background-size: @w @h;
    }
}

html {
    .at2x('_img/background.jpg', 1440px, 900px);
}

I tested this in 1.3.3 and 1.4 beta, both times it gave the following

CSS output:

html {
  background-image: url('http://mydomain.com/_img/background.jpg');
}
@media all and (-webkit-min-device-pixel-ratio: 1.5) {
  html {
    background-image: url('http://mydomain.com/_img/background@2x.jpg');
    background-size: 1440px 900px;
  }
}

Edit: As this uses javascript Andre noticed in a comment below, that it throws a parsing error in lessphp. So here is a way how you could do this only with LESS with no javascript, by feeding the mixin the file ending as a separate argument:

.at2x(@path, @sfx, @w: auto, @h: auto) {
    background-image: url('@{path}.@{sfx}');
    @media all and (-webkit-min-device-pixel-ratio : 1.5) {
        background-image: url('@{path}@2x.@{sfx}');
        background-size: @w @h;
    }
}

html {
    .at2x('_img/background', 'jpg', 1440px, 900px);
}

This solution should give the same result and does not require javascript. However, now you need to make sure you send the file name split in two arguments.

于 2013-04-02T06:11:28.510 回答