有什么方法可以将 Math.random() 传递给 jQuery .css()?

Any way to pass Math.random() to jQuery .css()?

我试图在每次将鼠标经过一个正方形 div 时生成随机颜色,但此代码不起作用。有没有简洁的方法来做到这一点?

$(this).css('background-color', 'rgb((Math.random()*255), (Math.random()*255),(Math.random()*255))')

这是整个街区:

$('.square').mouseenter(function () {
    if (fade === true) {
      $(this).css('background-color', '#6f418c');
    } else if (colors === true) {
      $(this).css('background-color', 'rgb((Math.random()*255), (Math.random()*255),(Math.random()*255))');
    } else {
      $(this).css('background-color', '#42145F');
    }
  });

一个css规则不能是javascript,你给'background-color'一个字符串值。 css 引擎不知道如何处理它。 你可以试试这个。

$(this).css('background-color','rgb(' +parseInt(Math.random()*255) +',' +parseInt(Math.random()*255) +',' +parseInt(Math.random()*255) +')')

注意:parseInt() 确保没有小数。

您尝试将随机数的 JavaScript 代码放入样式中。那行不通的。相反,您应该将随机数连接到字符串中。

var fade = false;
var colors = true;

$('.square').mouseenter(function () {
    if (fade === true) {
      $(this).css('background-color', '#6f418c');
    } else if (colors === true) {
      $(this).css('background-color','rgb(' + parseInt(Math.random()*255) + ',' + parseInt(Math.random()*255) + ',' + parseInt(Math.random()*255) + ')')
    } else {
      $(this).css('background-color', '#42145F');
    }
  });

我把代码放在这里: https://jsfiddle.net/smm9rbwa/