2011-12-24 33 views

回答

9

如果你創建一個SASS功能,因爲青菜是紅寶石它一樣容易打開的功能模塊,並注入您的隨機函數

module Sass::Script::Functions 
    module MyRandom 
    def random 
     rand(1.0) 
    end 
    end 
    include MyRandom 
end 

需要的文件SASS加載

後,那麼這是非常有可能的在樣式表

$my-randome-number: random(); 
3

是的,正如斯科特說,這是可能的,但我不是一個Rails程序員,所以我只是想複製和粘貼代碼,但第一個I D編號不知道在哪裏放置代碼,然後它不起作用。 我不得不玩的文檔片斷,並將其擴展到更多的靈活性,我有需要:

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 

THS可以在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文件中。

或者你把它放在另一個文件中,只把此行到您的指南針Config.rb文件:

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

更新:隨着薩斯3.3(2014),現在有一個內置random()功能:
http://sass-lang.com/documentation/Sass/Script/Functions.html#random-instance_method

$number: random() 

您也可以建立自己的簡單S中播種隨機函數屁股。實施例(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); 
} 

http://codepen.io/Sphinxxxx/pen/Gpmmye