【问题标题】:Set `background-color` property randomly once随机设置 `background-color` 属性一次
【发布时间】:2014-08-30 01:34:28
【问题描述】:

我正在为Anchor CMS 构建一个博客主题,我有一个关于随机分配背景颜色给 div 的问题。

我有一个工作脚本,它使用post 类为每个 div 随机分配一种颜色。我想知道的是我是否可以设置一次颜色 - 例如,在发布帖子时 - 并让它在每次页面加载时保持不变而不是重置。

这是我的功能:

$(".post").each(function randomColor() {
        var color = "#"+(Math.random()*0xFFFFFF<<0).toString(16);
        $(this).css("background-color", color)
      })

我想我可以使用 PHP 在博客注册表中创建一个数组,并根据帖子 ID 将值传递给它,但如果有更简单的方法,我不想使过程过于复杂。

一个不错的扩展,但不是必需的,就是在用户访问帖子时将该颜色带到帖子本身。

有什么想法吗?

编辑 - 您可以查看我的demo site 以了解主题的外观。随机颜色添加目前没有在那里实现。

【问题讨论】:

  • 颜色应该有多独特?
  • 您可以根据帖子的内容散列颜色,或者根据帖子的时间播种您的 rng。可能性是无穷无尽的。
  • 即使您创建了数组,您也必须存储它。如果您已经有一个数据库,则可以将其存储在那里。但是,如果您要存储将永远使用的颜色,为什么不直接选择颜色并对其进行硬编码
  • 或者你可以在一个巨大的静态 CSS 文件中用预先选择的随机颜色做一堆:nth-child(387)
  • 您是否知道帖子发布的时间戳?

标签: jquery css


【解决方案1】:

起初的一些考虑:

  1. 并非所有颜色都值得使用:所有可能的颜色都很多,但并非所有颜色都在页面中看起来不错(想想所有非常暗的颜色、灰色阴影等)。

  2. 即使你对它们的颜色保持一定的亮度,保持它们的可区分性也是一个好主意(例如,00FF00 和 00FE00 非常相似,甚至不会注意到)

    李>
  3. 您需要创建“有价值”颜色的子集。假设您想要 25 种不同的颜色(考虑到第 1 点和第 2 点,我认为这是公平的)。因此,每个 RGB 有 3 个不同的选择,即 3^3 = 27 减去 2,因为当所有三个都处于最大值并且所有三个都处于最小值时,它将是灰色的(不好)。

  4. 因此,您需要一个介于 1 到 25 之间的参数在所有帖子中足够随机,或者需要一个顺序参数(自动增量 ID?),以便在重新开始之前使用整套可能的颜色。


postID = /* get your post ID as int */

/* gets a number between 1 and 25 from your post ID */
colourID = (postID % 25) + 1 

/* this tells which "step" to use for each colour */
/* i.e. 20 in base 3 is "202" -> (2*9 + 0*3 + 2*1) = 18 + 2 = 20 */
/* so will keep "step 2" for red, "step 0" for green and "step 2" for blue */
base3ColourID = colourID.toString(3) 

/* this always returns 3 digits */
/* base3ColourID is 1 if ID is 1, we need "001" to have the colour "steps" */
niceB3CID = ("000").substring(base3ColourID.length) + base3ColourID 

/* calculate the actual colours */
red = 65 + 70*(parseInt(niceB3CID.charAt(0)))
green = 65 + 70*(parseInt(niceB3CID.charAt(1)))
blue = 65 + 70*(parseInt(niceB3CID.charAt(2)))

$('.post').css('background-color', "rgb("+red+","+green+","+blue+")")

HERE A FIDDLE IF YOU WANT TO PLAY WITH THEM COLOURS

编辑

编辑颜色范围以获得更好的颜色。

【讨论】:

  • 我喜欢这个,感谢您的解释。对于我的一生,我无法弄清楚如何以编程方式获取帖子 ID。对此有任何指示吗?
  • 你的意思是如何从 PHP 变量中获取 postID 到 JS?如果在您的帖子标签中是这样,您可以将 id 作为属性回显,例如 &lt;div class="post" data-id="&lt;? echo $postID; ?&gt;"&gt;,然后在 js 中 $('.post').each()$(this).attr('data-id')
【解决方案2】:

您可以使用发布帖子的年份 (0 - 365) 作为hsl 颜色中的第一个值(0 - 360,您可以为 360 之后的 5 天选择一个随机数)。

我认为使用hsl() 也是一个更安全的选择。你会知道你不会得到完全可怕的东西,颜色会有点相似。这是一个小演示......

http://jsbin.com/kagube/1/edit?html,css,output

【讨论】:

    【解决方案3】:

    注意,

    处可能有“bug”

    (Math.random()*0xFFFFFF&lt;&lt;0).toString(16)

    其中,偶尔,生成的字符串的length 可能是5,而不是6,导致没有background-color 应用于元素的style 的元素;例如,

    var arr = [], res = []; 
    for (i = 0; i < 100; i++) {
      arr.push((Math.random()*0xFFFFFF<<0).toString(16));
    };
    
    $.each(arr, function(k, v) {
      if (v.length < 6) {
        res.push(v);
      }
    });
    
    console.log(res.length);
    

    下面的部分包含快速修复解决方案

    试试

    html

    <!-- 
         given each "inner-container" element 
         within `.post` "outer-container"
         has some form of `unique-id` -->
    <div class="post">
        <span id="a"></span>
        <span id="b"></span>
        <span id="c"></span>
        <span id="d"></span>
        <span id="e"></span>
        <span id="f"></span>
        <span id="g"></span>
        <span id="h"></span>
    </div>
    

    js

    // this piece could actually be run when the "post" ,
    // or element , is generated , instead of each occasion
    // the document is loaded .
    // the `colors` array could be stored at server , 
    // as `json` object ,e.g., "colors.json", or other preferred format ,
    // updating when new "post" is created / generated .
    // the array generated could contain two members :
    // the unique "id" of the "post" , and the color
    // associated with that `unique-id`
    // the data could then be posted to server
    // which updates `colors.json` file with
    // new entries
    var colors = [];
        $(".post span").each(function(i, el) {
            // `bug` : occasionally returns string having 
            // `length` of `5` , instead of `6`
            var r = ((Math.random()*0xFFFFFF<<0).toString(16));
            // _quickix_ : check `length` of `r` string ,
            // if `< 6` , generate random "number" between 0-9 ,
            // concat to `r`
            r = r.length < 6 ? r + (1 + Math.floor(Math.random() * 9)) : r;
            var color = "#" + r ;
    
            // apply `color` to `background-color` , here ,
            // if desired
            // $(el).css("background-color", color);
    
            // push `unique-id , color` pair to `colors` array
            colors.push([el.id, color]);
    
            // optional , `POST` new `colors` array to server ,
            // adding new entry to `colors.json` ,
            // unique for each `unique-id`
            // $.post("colors.php", {"data" : colors});
          });
    
    // when loading "template" of `html` `.post` "posts" ,
    // having unique id's , or , being generated dynamically
    // and given `unique-id`'s , apply `color` to each element
    // based on `unique-id` and `color` generated for it
    // when created
    
    // optional : `$.getJSON("colors.json", function(colors) {});`
    // having `$.each()` function at `complete` callback 
    // reassembly `colors` associated with `unique-id`'s
    $.each(colors, function(k, v) {
       $(".post span[id="+v[0]+"]").css("background-color", v[1])
    });
    

    jsfiddle http://jsfiddle.net/guest271314/f895bh53/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 2014-12-12
      • 2021-07-28
      • 2021-05-23
      相关资源
      最近更新 更多