Покраска кнопок через input type color
Есть кнопки, которые красятся через input type color. Вопрос в том как сделать чтоб они красились в исходный цвет, то есть серый, при повторном нажатии и если выбран тот же цвет
document.addEventListener("click", function(e) {
var idColor = document.getElementById('idColor').value;
if_id = e . target. id;
the_class = e . target.className;
if(the_class == "click_me")
{
if_id = document.getElementById(if_id);
if(if_id .style . background == idColor)
{
if_id .style . background = "#efefef";
}
else
{
if_id .style . background = idColor;
}
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>
Choose color:
<input type="color" id="idColor">
</label>
<button class="click_me" id="id_1">Измени цвет кнопки</button>
<button class="click_me" id="id_2">Измени цвет кнопки</button>
<button class="click_me" id="id_3">Измени цвет кнопки</button>
</body>
</html>
Ответы (2 шт):
Автор решения: SwaD
→ Ссылка
const buttons = document.querySelectorAll('.click_me');
const colorSet = document.getElementById('idColor');
const defCol = '#c0c0c0'; // 192
const butColors = [];
function toHex (color) {
if (!color) return '';
color = color.replace('rgb(', '');
color = color.replace(')', '');
color = color.split(',');
color = '#' + color.map(c => {
let n = Number(c).toString(16);
if (n.length === 1) n = '0' + n;
return n;
}).join('')
return color;
}
buttons.forEach((item, index) => {
butColors.push(item.style.background ? item.style.background : defCol)
item.addEventListener('click', (e) => {
let color = toHex(e.currentTarget.style.background);
if (color !== colorSet.value) {
const forCh = color ? color : defCol;
e.currentTarget.style.background = colorSet.value;
butColors[index] = forCh;
} else {
e.currentTarget.style.background = butColors[index];
butColors[index] = colorSet.value;
}
})
})
<label>
Choose color:
<input type="color" id="idColor">
</label>
<button class="click_me" id="id_1">Измени цвет кнопки</button>
<button class="click_me" id="id_2">Измени цвет кнопки</button>
<button class="click_me" id="id_3">Измени цвет кнопки</button>
Автор решения: EzioMercer
→ Ссылка
Можно сделать добавив переключатель:
const newBGColor = document.querySelector('#idColor');
const oldBGColor = 'white';
const btns = document.querySelectorAll('.click_me');
document.addEventListener('click', (e) => {
const target = e.target;
if (!target.classList.contains('click_me')) return;
if (target.dataset.changed === '1') {
target.dataset.changed = '0';
target.style.backgroundColor = oldBGColor;
return;
}
target.dataset.changed = '1';
target.style.backgroundColor = newBGColor.value;
});
<label>
Choose color:
<input type="color" id="idColor">
</label>
<button class="click_me" id="id_1">Измени цвет кнопки</button>
<button class="click_me" id="id_2">Измени цвет кнопки</button>
<button class="click_me" id="id_3">Измени цвет кнопки</button>