изменить цвет фона каждой отдельной кнопки с помощью js - PullRequest
0 голосов
/ 06 марта 2020

Я хочу создать 31 кнопку с возможностью изменения цвета фона каждой отдельной кнопки. Проблема в том, что когда я пытаюсь изменить цвет кнопки 2, она меняет цвет кнопки 1.

Я пытаюсь сделать это на картинке Крест .

function myFunctionRed()
  {
    document.getElementById("myBtn").style.background = "green";
  }
  function myFunctionGreen()
  {
    document.getElementById("myBtn").style.background = "yellow";
  }
  function myFunctionBlue()
  {
    document.getElementById("myBtn").style.background = "red";
  }
// Get the modal
var modal = document.getElementById("myModal");
var modal2 = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var btn2 = document.getElementById("myBtn2");
// Get the <span> element that closes the modal

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function()
{
  modal.style.display = "block";
}
btn2.onclick = function()
{
  modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function()
{
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event)
{
  if (event.target == modal)
  {
    modal.style.display = "none";
  }
}
body
{
  font-family: Arial, Helvetica, sans-serif;
}
.modal
{
  display:none;
  background:#efefef;
  border:1px solid black;
  width:240px; height:100px;
}
.close
{
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
.close:hover,
.close:focus
{
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
#myBtn, #myBtn2
{
  background-color:gray;
  border: 0.5px solid black;
  color: white;
  width:30px;
  height:30px;
  border-radius: 10%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
#demo1
{
  background-color:green;
  border: none;
  color: white;
  width:60px;
  height:60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
#demo2
{
  background-color:yellow;
  border: none;
  color: white;
  width:60px;
  height:60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
#demo3
{
  background-color:red;
  border: none;
  color: white;
  width:60px;
  height:60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
  <button id="myBtn">1</button>
  <button id="myBtn2">2</button>
  <div id="myModal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <button id="demo1" onclick="myFunctionRed()">Red</button>
      <button id="demo2" onclick="myFunctionGreen()">Green</button>
      <button id="demo3" onclick="myFunctionBlue()">Blue</button>
    </div>
  </div>

Ответы [ 3 ]

1 голос
/ 06 марта 2020

меняет цвет кнопки 1

Это потому, что вы явно упоминаете только кнопку 1 id. Вместо id go с классом, а затем используйте querySelectorAll. Добавить прослушиватель событий к кнопкам, и из этого получить цель означает получить кнопку, на которую нажали.

Создать одну функцию для изменения цвета и передать цвет в качестве параметра функции.

var modal = document.getElementById("myModal");
let targetBtn;
document.querySelectorAll('.myBtn').forEach((item) => {
  item.addEventListener('click', (e) => {
    modal.classList.toggle('hide');
    targetBtn = e.target;

  })
})

function myFunction(color) {
  if (targetBtn) {
    targetBtn.style.background = color;
  }
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
body {
  font-family: Arial, Helvetica, sans-serif;
}

.modal {
  display: block;
  background: #efefef;
  border: 1px solid black;
  width: 240px;
  height: 100px;
}

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

.myBtn {
  background-color: gray;
  border: 0.5px solid black;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 10%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#demo1 {
  background-color: red;
  border: none;
  color: white;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#demo2 {
  background-color: green;
  border: none;
  color: white;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#demo3 {
  background-color: blue;
  border: none;
  color: white;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

.hide {
  display: none;
}
<button class="myBtn">1</button>
<button class="myBtn">2</button>
<div id="myModal" class="modal hide">
  <div class="modal-content">
    <span class="close">&times;</span>
    <button id="demo1" onclick="myFunction('red')">Red</button>
    <button id="demo2" onclick="myFunction('green')">Green</button>
    <button id="demo3" onclick="myFunction('blue')">Blue</button>
  </div>
</div>
0 голосов
/ 06 марта 2020

Все ваши функции обработчика ищут элемент с идентификатором myBtn, который является первой кнопкой. Вам нужно будет получить событие dom внутри обработчика кликов, разрешить targetElement и затем установить стиль для этого элемента.

См. Этот вопрос: JavaScript - onClick, чтобы получить идентификатор нажатой кнопки

Также см. Эти документы: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

0 голосов
/ 06 марта 2020

Привет, попробуйте использовать мой код:

// variable to track which button is activated
var activeButton = null;

function myFunctionRed() {
  document.getElementById(activeButton).style.background = "green";
}
function myFunctionGreen() {
  document.getElementById(activeButton).style.background = "yellow";
}
function myFunctionBlue() {
  document.getElementById(activeButton).style.background = "red";
}
// Get the modal
var modal = document.getElementById("myModal");
var modal2 = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var btn2 = document.getElementById("myBtn2");
// Get the <span> element that closes the modal

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
  // will make sure to return the color to gray
  btn2.style.backgroundColor = "gray";
  // set the value to myBtn
  activeButton = "myBtn";
};
btn2.onclick = function() {
  modal.style.display = "block";
  // will make sure to return the color to gray
  btn.style.backgroundColor = "gray";
  // set the value to myBtn2
  activeButton = "myBtn2";
};
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
};
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
};
...