I'm working on a project where I utilize SASS and Compass and need to somehow come up with some random numbers in the CSS file. Specifically, I need some floating point numbers between 0 and 1. Is this possible with SASS and Compass alone?
问题:
回答1:
This is very possible if you create a sass function since sass is ruby its as easy as opening the functions module and injecting your random function
module Sass::Script::Functions
module MyRandom
def random
rand(1.0)
end
end
include MyRandom
end
require the file after sass has loaded
Then in your stylesheet
$my-randome-number: random();
回答2:
Yes, as Scott said, it is possible, but I am not a Rails programmer, so I just wanted to copy and paste the code but first I did not know where to place the Code and then it did not work. I had to play around with the snipped and expanded it to more Flexibility that I had need for:
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 can be used in a SCSS file like this:
@debug usw_random();
@debug usw_random(10);
@debug usw_random(8, 2);
@debug usw_randomColor();
and will printout:
xxx.scss:25 DEBUG: 0.42782
xxx.scss:26 DEBUG: 3
xxx.scss:27 DEBUG: 5
xxx.scss:28 DEBUG: #e7c00b
I also did not know where to put the Code for this. I use SASS within compass framework. You can place this Code directly into your Compass Config.rb file.
Or you put it in another file and only put this line into your Compass Config.rb file:
## my "own" ruby functions.
require "../SASS/RUBY/at.usw.rb"
回答3:
Update: With Sass 3.3 (2014), there is now a built-in random()
function:
http://sass-lang.com/documentation/Sass/Script/Functions.html#random-instance_method
$number: random()
You can also build your own simple seeded random function in Sass. Example (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