0
votes

Bouton pour changer de couleur d'arrière-plan au hasard

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    document.body.style.backgroundColor = changeC()
});

var x = Math.floor(Math.random() *256);
    y = Math.floor(Math.random() * 256);
    z = Math.floor(Math.random() * 256);

function changeC() { 
    return  "rgb(" + x + "," + y + "," + z + ")";
};
First click changes the background color.
Consecutive clicks don't.
How to modify code so that consecutive clicks will also change the background color randomly?

2 commentaires

mettre la fonction x y z


Notez que y et z ne faisant pas partie de var car var terminé par un point-virgule ( < / code>). Ajouter var avant y et z ou, remplacez le point-virgule après x et y à une virgule (, ).


5 Réponses :


0
votes

Exécuter ce code

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<button id="btn">change color</button>

<script>
const btn = document.getElementById('btn');


btn.addEventListener('click', () => {
    document.body.style.backgroundColor = changeC()
});


function changeC() { 

var x = Math.floor(Math.random() * 256);
    y = Math.floor(Math.random() * 256);
    z = Math.floor(Math.random() * 256);
    return  "rgb(" + x + "," + y + "," + z + ")";
};

</script>

</body>
</html>


0 commentaires

1
votes

Votre x code> y code> et z code> n'a été attribué qu'une seule fois, car le programme a démarré, car ils étaient à la portée de haut niveau . Pour les réaffecter à chaque fois, déplacez-les dans la fonction comme indiqué.

const btn = document.getElementById('btn');


btn.addEventListener('click', () => {
    document.body.style.backgroundColor = changeC()
});

function changeC() { 
    var x = Math.floor(Math.random() *256),
        y = Math.floor(Math.random() * 256),
        z = Math.floor(Math.random() * 256);

    return  "rgb(" + x + "," + y + "," + z + ")";
};


1 commentaires

@iamoren a souligné, votre y et z ne faisiez pas partie de la déclaration var . J'ai corrigé cela dans ma réponse en utilisant , au lieu de ; . Auparavant, cela aurait fonctionné, mais y et z aurait été des variables globales au lieu de la fonction locale à la fonction ChangeC .



0
votes

Mettez à jour votre fonction identique à suivre:

function changeC() { 
    x = Math.floor(Math.random() *256);
    y = Math.floor(Math.random() * 256);
    z = Math.floor(Math.random() * 256);
    return  "rgb(" + x + "," + y + "," + z + ")";
};


0 commentaires

0
votes

<h1>This works</h1>
<button id="btn"> PRESS ME </button>


0 commentaires

0
votes

Essayez ceci:

p>

<button id="btn">
  Click me
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


0 commentaires