если у нас есть на моей странице index.html :
<span class = "token-label" style = "max-width: 1072px;">Hello world</span>
<span class = "token-label" style = "max-width: 1072px;">Bye world</span>
на странице у нас есть форма, содержащая поля:
Hello world Bye world
я хочу: когда я нажму на одно из этих двух полей, я получу небольшой список ниже: горит 3 цвета, и я выбираю цвет, чтобы покрасить фон этого поля этим цветом, в javascript, пожалуйста
я новичок в javascript, я не знаю, как мы можем это сделать, пожалуйста, помогите, я только что попытался получить значение «Hello world» следующим образом:
document.getElementsByClassName('token-label')[0].textContent
Я ищу в Интернете и нахожу: тег переключения контейнера с цветом... но я не понимаю.
Я могу предоставить скрипт, у меня он работает, так что он должен работать.
#token-label {
background-color: ; /* Set your background color */
}
JavaScript:
var colors = ["#"]; // Set the background color you want to change
var colorIndex = 0;
function changeColor() {
var col = document.getElementById("token-label");
if ( colorIndex >= colors.length ) {
colorIndex = 0;
}
if (colors[colorIndex] == col.getAttribute("currentColor")){
col.style.backgroundColor = null;
col.setAttribute("currentColor",col.style.backgroundColor);
}
else {
col.style.backgroundColor = colors[colorIndex];
col.setAttribute("currentColor",colors[colorIndex]);
}
colorIndex++;
}
И измените class = "token-label"
на id = "token-label"
Дайте мне знать, если это сработает, если нет, возможно, я ошибся, поэтому я могу это изменить.
самое простое решение в ванильном javascript должно выглядеть как фрагмент ниже
я правильно понял ваш вопрос?
// obtain elements
const htmlCollection = document.getElementsByClassName("token-label");
const array = [...htmlCollection];
// add listener to show the palette
array.forEach(span => span.addEventListener("click", modifyColor, false));
function modifyColor(mouseEvent) {
const target = mouseEvent.currentTarget;
const x = mouseEvent.clientX;
const y = mouseEvent.clientY;
function colorChosen(color) {
target.style.backgroundColor = color;
}
showPalette({ x, y }, colorChosen);
}
function createDiv(style) {
const div = document.createElement("div");
Object.entries(style)
.forEach(([property, value]) => div.style[property] = value);
return div;
}
function showPalette({ x, y }, callback) {
// palette itself
const paletteElement =
createDiv({
position: "absolute",
left: `${x}px`,
top: `${y}px`
});
document.body.append(paletteElement);
// here you can redefine html colors
const colors = ["LightSalmon", "LightGreen", "LightBlue"];
// each color creation and adding click listeners
colors.forEach(colorValue => {
const colorElement = createDiv({
width: "40px",
height: "20px",
backgroundColor: colorValue
});
colorElement.addEventListener("click", () => {
cleanup();
callback(colorValue);
}, false);
paletteElement.append(colorElement);
});
// don't forget to remove palette from document
function cleanup() {
document.body.removeChild(paletteElement);
}
}
<span class = "token-label" style = "max-width: 1072px;">Hello world</span>
<span class = "token-label" style = "max-width: 1072px;">Bye world</span>