【问题标题】:How to pick random content from an array如何从数组中选择随机内容
【发布时间】:2014-12-26 19:09:33
【问题描述】:

我正在尝试提供从 Less 数组中挑选的随机图像。

这是我目前所拥有的:

@images = ['ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg'];
@randomimage: `images[Math.floor(Math.random() * images.length)]`;
 
#footer-widgets .container .row {
    background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}

我想我正在做一些语法错误。这是在 URL (path/@{randomimage}) 中调用变量的方式吗?

【问题讨论】:

  • 看你的LESS我看到一些JS,可以吗?此外,您的 LESS 将被转换为 CSS 并且 CSS 是静态的,在编译 LESS 时选择一次的图像。注意:我不使用 LESS,几乎不知道它的语法。
  • 根据这个答案似乎有可能:stackoverflow.com/a/19869095/1342772

标签: css less


【解决方案1】:

您的代码的一个工作示例可以在下面找到:

@images: 'ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg';
@length: length(@images);
@random: `Math.ceil(Math.random() * (@{length}))`;
@randomimage: extract(@images,@random);

#footer-widgets .container .row {
    background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}

注意,Less 中的“数组”可以定义为列表,另见:Loop through array of variable names in Less Less列表的第一个索引是1

除非您编译您的 Less 代码客户端(为每个请求重新编译代码),否则您应该考虑 @Random-User 的注释。事实上,编译后的 CSS 是静态的,随机化似乎没有意义。

【讨论】:

  • 输出是@randomimage: extract(@images,@random); #footer-widgets .container .row{background:url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0)} 好像extract 没有被解析。我正在使用 Automattic Jetpack 中包含的 LESS 预处理器
  • 可能预处理器根本不支持原生javascript调用。
猜你喜欢
  • 2011-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多