suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Wie ändere ich die Hintergrundfarbe eines Div mit jQuery? [geschlossen]

Ich möchte die Hintergrundfarbe eines Div zur Laufzeit mithilfe von JQuery ändern. Das Div wird angezeigt, aber seine Hintergrundfarbe ändert sich nicht. Ich weiß nicht, was mit dem Code, den ich geschrieben habe, falsch ist.

<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()
            {
                r = Math.floor(Math.random()*256);
                g = Math.floor(Math.random()*256);
                b = Math.floor(Math.random()*256);

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

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

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

Ich möchte einen dezimalen RGB-Wert.

P粉585541766P粉585541766515 Tage vor622

Antworte allen(1)Ich werde antworten

  • P粉854119263

    P粉8541192632023-09-17 20:45:11

    你需要使用Math.floor函数而不是floor(当前代码中未定义floor,这就是为什么你的r g b值无效的原因):

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <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() {
                var r = Math.floor(Math.random() * 256);
                var g = Math.floor(Math.random() * 256);
                var b = Math.floor(Math.random() * 256);
                var rgb_ = "rgb(" + r + ", " + g + ", " + b + ")";
                $("#color").css("background-color", rgb_);
            }
    
            setInterval(change_color, 1000);
        </script>
    </body>
    </html>

    Antwort
    0
  • StornierenAntwort