меняет цвет кнопки 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">×</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>