我正在开发一个利用SASS和Compass的项目,需要以某种方式在CSS文件中提出一些随机数。具体来说,我需要一些介于0和1之间的浮点数。这是否可以单独使用SASS和Compass?
答案 0 :(得分:9)
如果你创建一个sass函数,这是很有可能的,因为sass是ruby,就像打开函数模块和注入随机函数一样简单
module Sass::Script::Functions
module MyRandom
def random
rand(1.0)
end
end
include MyRandom
end
在sass加载后需要文件
然后在你的样式表中
$my-randome-number: random();
答案 1 :(得分:3)
是的,正如斯科特所说,这是可能的,但我不是Rails程序员,所以我只想复制并粘贴代码,但首先我不知道在何处放置代码然后它不起作用。 我不得不玩剪切并将其扩展到我需要的更多灵活性:
module Sass::Script::Functions
module USW_Random
## Create random Color
# inspired by: http://victorcoulon.fr/generating-random-color-in-sass/
#
def usw_randomColor()
Sass::Script::Color.new([rand(255), rand(255), rand(255)])
end
## Create random Number
# int max [optional] if max is not supplied a float between 0 and 1 is returned.
# if max is supplied, an Integer between 0 and max (both inclusive) will be returned.
# int min [optional] if min is supplied too, an Integer between min and max (both inclusive) will be returned.
#
def usw_random(max=-1, min=0)
Sass::Script::Number.new( max.to_i < 0 ? rand() : rand(min.to_i .. max.to_i ))
end
end
include USW_Random
end
可以在这样的SCSS文件中使用:
@debug usw_random();
@debug usw_random(10);
@debug usw_random(8, 2);
@debug usw_randomColor();
并将打印输出:
xxx.scss:25 DEBUG: 0.42782
xxx.scss:26 DEBUG: 3
xxx.scss:27 DEBUG: 5
xxx.scss:28 DEBUG: #e7c00b
我也不知道在哪里放置代码。我在罗盘框架内使用SASS。您可以将此代码直接放入Compass Config.rb文件中。
或者您将它放在另一个文件中,只将此行放入Compass Config.rb文件中:
## my "own" ruby functions.
require "../SASS/RUBY/at.usw.rb"
答案 2 :(得分:1)
更新:使用Sass 3.3(2014),现在有一个内置的random()
功能:
http://sass-lang.com/documentation/Sass/Script/Functions.html#random-instance_method
$number: random()
您还可以在Sass中构建自己的简单种子随机函数。示例(SCSS):
/* YOUR SEED HERE: */
$seed: 369;
@function getRandom($max) {
//http://indiegamr.com/generate-repeatable-random-numbers-in-js/
//Note the "!global" flag:
//http://webdesign.tutsplus.com/articles/understanding-variable-scope-in-sass--cms-23498
$seed: ($seed * 9301 + 49297) % 233280 !global;
@return ($seed / 233280) * $max;
}
.my-class {
height: getRandom(200) + px;
opacity: getRandom(1);
}