Css 是否可以在SASS/Compass中创建随机数?

Css 是否可以在SASS/Compass中创建随机数?,css,sass,compass-sass,Css,Sass,Compass Sass,我正在做一个项目,在这个项目中,我使用SASS和Compass,需要在CSS文件中找到一些随机数。具体来说,我需要一些介于0和1之间的浮点数。仅使用SASS和Compass就可以做到这一点吗?如果您创建一个SASS函数,这是非常可能的,因为SASS是ruby的,只需打开函数模块并注入随机函数即可 module Sass::Script::Functions module MyRandom def random rand(1.0) end end inclu

我正在做一个项目,在这个项目中,我使用SASS和Compass,需要在CSS文件中找到一些随机数。具体来说,我需要一些介于0和1之间的浮点数。仅使用SASS和Compass就可以做到这一点吗?

如果您创建一个SASS函数,这是非常可能的,因为SASS是ruby的,只需打开函数模块并注入随机函数即可

module Sass::Script::Functions
  module MyRandom
    def random
      rand(1.0)
    end
  end
  include MyRandom
end
加载sass后需要该文件

然后在样式表中

$my-randome-number: random();

是的,正如Scott所说,这是可能的,但我不是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
并将打印出:

xxx.scss:25 DEBUG: 0.42782
xxx.scss:26 DEBUG: 3
xxx.scss:27 DEBUG: 5
xxx.scss:28 DEBUG: #e7c00b
我也不知道该把代码放在哪里。我在compass框架中使用SASS。您可以将此代码直接放入Compass Config.rb文件中

或者您将其放在另一个文件中,并仅将这一行放在Compass Config.rb文件中:

## my "own" ruby functions. 
require "../SASS/RUBY/at.usw.rb"

更新:使用Sass 3.3(2014),现在有一个内置的
random()
函数:

您还可以在Sass中构建自己的简单种子随机函数。示例(SCSS):

## my "own" ruby functions. 
require "../SASS/RUBY/at.usw.rb"
$number: random()
/* 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);
}