1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| <!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multi états au clic</title>
<meta name="Author" content="NoSmoking">
<meta name="DVP-discussion" content="d2092219">
<style>
html,body{margin:0;padding:0;font:1em/1.5 Verdana,sans-serif}
h1,h2,h3{margin:.25em 0;color:#069}
time{float:right;margin:.5em;font-size:.9em;color:#888}
main{display:block;margin:auto;max-width:60em}
.row {
display: flex;
align-items: center;
width: fit-content;
margin-bottom: .5em;
padding: .25em;
border: 3px double #888;
}
.circle,
.click {
width: 5em;
height: 5em;
margin: .5em;
border: 1px solid #888;
text-align: center;
line-height: 5;
background-color: whitesmoke;
cursor: pointer;
}
.circle {
border-radius: 50%;
background-color: white;
}
</style>
</head>
<body>
<main>
<header>
<time datetime="2020-10-01">Oct. 2020</time>
<h1>Multi états au clic</h1>
</header>
<div class="row">
<div class="click">Tél.</div>
<div class="click">Exploit.</div>
<div class="circle"></div>
</div>
<div class="row">
<div class="click">Sono</div>
<div class="click">Pupitre</div>
<div class="click">Volume</div>
<div class="circle"></div>
</div>
</main>
<script>
"use strict";
// définition des différentes couleurs
const COLOR = "whitesmoke;orange;lightgreen".split(";");
const COLOR_NOK = COLOR[1];
const COLOR_OK = COLOR[2];
function updateCircle(parent) {
// éléments à traiter
const oCircle = parent.querySelector(".circle");
const oCount = parent.querySelectorAll(".click");
let color = ""; // restaure couleur par défaut du CSS
let nbVert = 0;
let nbOrange = 0;
// récup. état des clicks
const etats = [0, 0, 0];
oCount.forEach((el) => {
etats[el.countClick] += 1;
});
// pour plus de clarté
nbOrange = etats[1];
nbVert = etats[2];
// traitement résultat
if (nbOrange) {
color = COLOR_NOK;
}
else if (nbVert) {
color = nbVert == oCount.length ? "" : COLOR_OK;
}
// affectation de la couleur
oCircle.style.backgroundColor = color;
}
// récup. des éléments cliquables
const oClick = document.querySelectorAll(".click");
// affectation action
oClick.forEach((el) => {
el.addEventListener("click", (ev) => {
const count = el.countClick || 0;
el.countClick = (count + 1) % COLOR.length;
el.style.backgroundColor = COLOR[el.countClick];
updateCircle(el.parentNode);
})
});
</script>
</body>
</html> |
Partager