解释为什么这个HTML只适用于Firefox,而不适用于任何其他浏览器?

Raj*_*was 1 html javascript css jquery

大家.我在HTML/CSS/Javascript中大约一周大的初学者.我为一个页面编写了这个代码,该页面用于在鼠标在页面上移动时根据"随机"RGB值(始终为alpha值固定为1)更改颜色.

<!DOCTYPE html>
<head>
  <script src='https://code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>
  <script>
    $('*').mousemove(function() {
      var red = Math.floor(Math.random() * 255);
      var green = Math.floor(Math.random() * 255);
      var blue = Math.floor(Math.random() * 255);

      var rgba = 'rgba(' + red + ',' + blue + ',' + green + ')';
      $('*').css('background', rgba);
    });
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)

我尝试过Chrome,Chromium,Vivaldi,Opera甚至是Internet Explorer,所有这些浏览器都显示了一个网页,其默认的白色背景页面对鼠标移动没有反应.

Ror*_*san 6

您的代码的主要问题是您正在设置RGBA颜色,但您忘记提供A值.

我也建议你使用document监听的mousemove事件和更新background-colorbody.*应尽可能避免使用通配符选择器,因为它很慢 - 尤其是在附加事件处理程序时.

$(document).mousemove(function() {
  var red = Math.floor(Math.random() * 255);
  var green = Math.floor(Math.random() * 255);
  var blue = Math.floor(Math.random() * 255);

  var rgba = 'rgba(' + red + ',' + blue + ',' + green + ',1)'; // note '1' at the end
  $('body').css('background', rgba);
});
Run Code Online (Sandbox Code Playgroud)
<script src='https://code.jquery.com/jquery-1.10.2.js'></script>
Run Code Online (Sandbox Code Playgroud)

这个片段应该有癫痫警告......

  • 在Firefox中,也许,因为它假设您打算添加它.但是其他浏览器从字面上理解值,如果它没有正确形成 - 如问题中的示例 - 则忽略该设置.这就是你*需要*包含alpha值的原因. (2认同)
  • @RajdeepBiswas这不在您的代码中,请尝试更加感激.我可以确认Rory的代码段在Chrome中有效. (2认同)