You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery修改div背景颜色?代码异常排查求助

问题分析与解决:jQuery无法修改div背景色

你的代码无法修改背景色的核心原因是调用取整方法时缺少Math.前缀:JavaScript中floor是Math对象的内置方法,直接写floor()会触发"未定义"错误,导致整个change_color函数执行失败。

修正步骤:

  • 将所有floor()替换为Math.floor(),确保正确调用取整方法
  • (可选规范)给变量r、g、b、rgb添加let声明,避免全局变量污染

修正后的完整代码:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
        <div id="color" style="width:100px;height:100px;background-color:grey;">Hello, world!</div>
        <script>
            function change_color()
            {
                let r = Math.floor(Math.random()*256);
                let g = Math.floor(Math.random()*256);
                let b = Math.floor(Math.random()*256);

                let rgb = "rgb(" + r + ", " + g + ", " + b + ")";

                $("#color").css("background-color", rgb);
            }

            setInterval(change_color, 1000);
        </script>
    </body>
</html>

内容的提问来源于stack exchange,提问作者Raghav Indra Singh DiCaprio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:37:07