随机生成颜色并保存在CSS中

Random generated colors and saving them in CSS

本文关键字:存在 CSS 保存 颜色 随机      更新时间:2023-09-26

我不能百分百地解释这一点,因为如果我能的话,我可能会弄清楚。

我正在为聊天室编写代码。我想使用javascript随机生成一个颜色,并将其分配给某人的名字。但它只会分配一次,当他们键入新消息时,它会默认。我怎样才能让颜色粘住呢?这是我目前所看到的:

$(document).ready(function() {
$('.username').each(function () {
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
    $(".username").css("color", hue);
}); });

尝试在每个函数中使用$(this)代替$(".username"):

$('.username').each(function () {
    var hue = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
    $(this).css("color", hue);
});