有没有办法将Math.random()传递给jQuery .css()?

时间:2015-09-05 22:05:57

标签: jquery colors rgb

我试图在每次将鼠标移到方形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');
    }
  });

2 个答案:

答案 0 :(得分:0)

css规则不能是javascript,你给'background-color'一个字符串值。 css引擎不知道该怎么做。 你可以试试这个。

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

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

答案 1 :(得分:0)

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

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/