JavaScript DOM - Как разрешить пользователю выбирать только один вариант - PullRequest
0 голосов
/ 14 июля 2020

Я делаю игру «камень, ножницы, бумага» с помощью HTML, CSS и JS DOM. У меня есть 6 кнопок, которые позволяют вам выбрать, сколько раундов вы хотите сыграть. Я хочу, чтобы при нажатии на один из них он становился темнее. Затем, когда вы щелкнете по другому, он станет темнее, а предыдущий станет более светлым. Кто-нибудь знает, как бы я это реализовал? Любая помощь будет принята с благодарностью :)

// Changes button color when clicked
let rounds = document.querySelectorAll(".rounds");
rounds.forEach(i => {
    i.addEventListener("click", () => {
        i.style.cssText = "color: gray; border-color: gray";
    });
});
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}
<div id="rounds">
    <button class="rounds">Best of 1</button>
    <button class="rounds">Best of 3</button>
    <button class="rounds">Best of 5</button>
    <button class="rounds">Best of 7</button>
    <button class="rounds">Best of 10</button>
    <button class="rounds">Custom</button>
  </div>

Ответы [ 4 ]

0 голосов
/ 14 июля 2020

Если вы не хотите использовать классы, вы можете использовать прослушиватель событий div для прослушивания кнопки, запускающей событие, а затем l oop через элемент установите их на белый цвет, а кнопку на серый, чтобы установить цвет кнопки в javascript вы делаете element.style.color="white"

// Changes button color when clicked

let rounds = document.querySelectorAll(".rounds");
buttons=document.getElementById("rounds")
  buttons.addEventListener("click", (e) => {
rounds.forEach(i => {
     i.style.color=" white"         
     i.style.borderColor="white"

});
    e.target.style.color = "gray";
    e.target.style.borderColor= "gray"
   
});
</script>
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}
<div id="rounds">
    <button class="rounds">Best of 1</button>
    <button class="rounds">Best of 3</button>
    <button class="rounds">Best of 5</button>
    <button class="rounds">Best of 7</button>
    <button class="rounds">Best of 10</button>
    <button class="rounds">Custom</button>
  </div>
0 голосов
/ 14 июля 2020

// Changes button color when clicked
let rounds = document.querySelectorAll(".rounds");
rounds.forEach(i => {
    i.addEventListener("click", () => {
        [...rounds].map(el => el.style.cssText = "color: white; border-color: white");
        i.style.cssText = "color: gray; border-color: gray";
    });
});
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}
<div id="rounds">
    <button class="rounds">Best of 1</button>
    <button class="rounds">Best of 3</button>
    <button class="rounds">Best of 5</button>
    <button class="rounds">Best of 7</button>
    <button class="rounds">Best of 10</button>
    <button class="rounds">Custom</button>
  </div>

Совет: попробуйте переключить имя класса вместо изменения css

0 голосов
/ 14 июля 2020

Возможно, это поможет вашему проекту, одновременно можно выбрать только одну радиокнопку в группе, например:

<input type="radio" name="rounds" id="1">Best of 1
<input type="radio" name="rounds" id="3">Best of 3
<input type="radio" name="rounds" id="5">Best of 5
<input type="radio" name="rounds" id="7">Best of 7
<input type="radio" name="rounds" id="10">Best of 10
0 голосов
/ 14 июля 2020

Добавьте al oop, который меняет цвета всех остальных кнопок.

Было бы проще, если бы вы использовали для этого классы, а не назначать cssText.

// Changes button color when clicked
let rounds = document.querySelectorAll(".rounds");
rounds.forEach(i =>
  i.addEventListener("click", () => {
    rounds.forEach(r => r.classList.remove("active"));
    i.classList.add("active");
  })
);
* {
  color: white;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: black;
  font-family: Arial, Helvetica, sans-serif;
}

#rounds {
  display: grid;
  justify-content: center;
  grid-template-columns: repeat(3, 0.2fr);
  grid-template-rows: repeat(2, 0.2fr);
  grid-gap: 10px;
  margin-top: 30px;
}

.rounds {
  background-color: black;
  font-size: 25px;
  border: solid 8px white;
  outline: none;
  padding: 5px 0;
}

.rounds:hover {
  cursor: pointer;
  color: lightgray;
  border-color: lightgray;
}

.rounds.active {
  color: gray;
  border-color: gray;
}
<div id="rounds">
  <button class="rounds">Best of 1</button>
  <button class="rounds">Best of 3</button>
  <button class="rounds">Best of 5</button>
  <button class="rounds">Best of 7</button>
  <button class="rounds">Best of 10</button>
  <button class="rounds">Custom</button>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...