最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I generate a random color with Stylus CSS? - Stack Overflow

programmeradmin0浏览0评论

I'm using Express for Node.js and the CSS engine I'm using is Stylus. Stylus is awesome except I can't seem to figure out how to pass in a color variable or otherwise generate a random color. I tried using the javascript API for stylus but I'm just confusing myself and probably over-plicating things.

var stylus = require('stylus');

app.use(stylus.middleware({
  src: __dirname + '/public',
  pile: function (str, path) {
    var mylib = function(style) {
      style.define('randomColor', function () {
        return '#5f5'; // temporary color just to see if it's working.
      });
    };
    return stylus(str).use(mylib);
  }
}));

Then in my stylus sheet I do:

mainColor = randomColor()

However, I get the following error:

RGB or HSL value expected, got a string #5f5

I for the life of me cannot figure out how to properly pass a color variable into the stylus sheet from javascript.

Edit:

Here is my app.js file:
Here is my Stylus file:

I'm using Express for Node.js and the CSS engine I'm using is Stylus. Stylus is awesome except I can't seem to figure out how to pass in a color variable or otherwise generate a random color. I tried using the javascript API for stylus but I'm just confusing myself and probably over-plicating things.

var stylus = require('stylus');

app.use(stylus.middleware({
  src: __dirname + '/public',
  pile: function (str, path) {
    var mylib = function(style) {
      style.define('randomColor', function () {
        return '#5f5'; // temporary color just to see if it's working.
      });
    };
    return stylus(str).use(mylib);
  }
}));

Then in my stylus sheet I do:

mainColor = randomColor()

However, I get the following error:

RGB or HSL value expected, got a string #5f5

I for the life of me cannot figure out how to properly pass a color variable into the stylus sheet from javascript.

Edit:

Here is my app.js file: https://gist.github./4345823
Here is my Stylus file: https://gist.github./4345839

Share Improve this question edited Dec 20, 2012 at 15:12 ChevCast asked Dec 20, 2012 at 15:02 ChevCastChevCast 59.3k66 gold badges221 silver badges325 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 5

I know this is an exceptionally late answer, but what's worth documenting should never go ignored - the problem, as you have identified, is that Stylus is receiving a string, when it should be receiving an RGB or HSL colour node.

Strings in Stylus look like this: 'text', and when they get piled to CSS, they get piled as-is. You need to render plain CSS text, not a string.

Stylus has a built-in function that you can use to turn that string into plain CSS text: unquote()

So you could simply change the line from

mainColor = randomColor()

to

mainColor = unquote(randomColor())

However, if you want to keep your Stylus clean, you might want to make use of the Stylus JavaScript API's nodes object. If you're passing a function from JavaScript to Stylus, consider it a best practice to return a Stylus node rather than a primitive data type:

style.define('randomColor', function () {
  var randomNum = function() { return Math.floor(Math.random() * 255 + 1); },
      r = randomNum(),
      g = randomNum(),
      b = randomNum();
  return new stylus.nodes.RGBA(r, g, b, 1); // random RGB node.
});

Sadly, there isn't much documentation on Stylus Nodes, but all you really need as a reference is this. It contains all of the available nodes.

you can generate random color by

 var col =  rgb(‘ + 
              (Math.floor(Math.random() * 256)) 
             + ‘,’ + (Math.floor(Math.random() * 256)) 
             + ‘,’  + (Math.floor(Math.random() * 256)) + ‘) ;

or

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

and to convert hex to rgb

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

I ended up generating classes for an array of colors and using javascript to change the classes randomly at regular intervals.

// css.styl

colors = 0 30 60 90 120 150 180 210 240 270 300 330

for hue, index in colors
  color = hsl(hue, 100%, 75%)
  .bodyColor{index}
    color: lighten(color, 55%) !important
    //background-color: darken(color, 97%) !important
  .borderColor{index}
    border-color: darken(color, 65%) !important
  a.linkColor{index}, a.linkColor{index}:visited
    color: lighten(color, 85%)
  .containerColor{index}
    background-color: color !important
  a.buttonColor{index}
    color: darken(color, 75%) !important
    background-color: lighten(color, 25%)
  a.buttonColor{index}:hover
    background-color: darken(color, 50%)
    color: lighten(color, 85%) !important

// animateColor.js

(function ($) {

  $(document).bind('initialize', function (e) {
    if (!e.firstLoad) return;

    var colorIndex = 3,
      delay = 10,
      items = [
        { element: 'body', cssClass: 'bodyColor' },
        { element: '#banner', cssClass: 'borderColor' },
        { element: 'a', cssClass: 'linkColor' },
        { element: '.translucentFrame', cssClass: 'containerColor' },
        { element: 'a.button', cssClass: 'buttonColor' }
      ];

    $(document).data('colorItems', items);

    (function changeColors() {
      items.forEach(function (item) {
        $(item.element).removeClass(item.cssClass + colorIndex);
      });

      colorIndex = Math.floor(Math.random()*11);
      $(document).data('colorIndex', colorIndex);

      items.forEach(function (item) {
        $(item.element).addClass(item.cssClass + colorIndex);
      });

      setTimeout(changeColors, delay * 1000);
    })();
  });

})(jQuery);

I know this is incredibly late, but I stumbled on this through google and the easiest solution I found was to do this:

random(min, max)
  return floor( math(0, "random") * max + min )
randomColorChannel()
  return random(0, 255)
randomColor()
  return rgb(randomColorChannel(), randomColorChannel(), randomColorChannel())
发布评论

评论列表(0)

  1. 暂无评论