如何根据调色板的选择更改图像的颜色

时间:2019-01-26 15:59:51

标签: javascript

我有一张要更改颜色的图像,我有<ul>种颜色,所有颜色都以小方块显示。我想根据用户单击的框来修改图像的颜色。

  <li swatch="3FB8AF"></li>
  <li swatch="7FC7AF"></li>
  <li swatch="DAD8A7"></li>
  <li swatch="FF9E9D"></li>
  <li swatch="FF3D7F"></li>

例如如果有人点击<li swatch="7BE0D0"></li>,则图像应更改为该颜色。

2 个答案:

答案 0 :(得分:0)

我不明白你所说的颜色是什么意思。这是更改颜色div的示例

<html>
<head>
</head>
<body>

<ul id="colors">
<li swatch="#3FB8AF"></li>
<li swatch="#7FC7AF"></li>
<li swatch="#DAD8A7"></li>
<li swatch="#FF9E9D"></li>
<li swatch="#FF3D7F"></li>
</ul>
<div style="height:500px;width:500px;font-size:50px" id="mainElm">Elment whose color will change</div>

<script>
var colors = document.querySelectorAll('ul#colors > li');
for(let color of colors){
    color.style.backgroundColor = color.getAttribute("swatch");
    color.style.height = "50px";
    color.style.width = "50px";
    color.onclick = function(){
        document.getElementById('mainElm').style.backgroundColor = color.getAttribute('swatch');
    }
}

</script>
</body>

</html>

答案 1 :(得分:0)

尚不清楚您通过修改图像的颜色表示什么。但是,这里有一个示例,该示例将背景色添加到每个色板方块,单击侦听器到其容器,以及一个函数,当单击色板方块时,将颜色添加到另一个元素。它将使您对自己编写代码时所需的步骤有所了解。

1)您应该在HTML中使用数据属性。 data-color="3FB8AF"而非swatch="3FB8AF",以确保您的HTML有效。

2)我正在使用"event delegation"。除了向每个color元素添加一个侦听器之外,您还可以向contains元素添加一个侦听器,该侦听器在包含事件的DOM从其子级冒起时捕获事件。

希望这会有所帮助。

// Cache the swatch element (the `ul`), and add
// an event listener to it. This calls `handleClick`
// when it is clicked or any of its child elements are clicked
const swatch = document.querySelector('ul');
swatch.addEventListener('click', handleClick, false);

// Cache the color squares in the swatch, and the "image" element
const colorSquares = document.querySelectorAll('li');
const img = document.querySelector('.image');

// Destructures the dataset from the element that
// was clicked and calls `setColor`, passing in the
// element to which we need to apply the color
function handleClick(e) {
  const { dataset: { color } } = e.target;
  setColor(img, color);
}

// Accepts an element and a color - sets
// the background color of the element.
// Note: because the data-color attribute doesn't
// contain a preceding hash we have to add it here 
function setColor(el, color) {
  el.style.backgroundColor = `#${color}`;  
}

// Iterates over the color squares and set each
// of their background color to the hex color in the
// dataset
[...colorSquares].forEach(colorSquare => {
  const { dataset: { color } } = colorSquare;
  setColor(colorSquare, color);
});
ul { padding-left: 0; display: flex; flex-direction: row; list-style-type: none; }
li { height: 20px; width: 20px; }
li:hover { cursor: pointer; }
.image { text-align: center; border: 1px solid #676767; height: 50px; width: 100px; }
<ul>
  <li data-color="3FB8AF"></li>
  <li data-color="7FC7AF"></li>
  <li data-color="DAD8A7"></li>
  <li data-color="FF9E9D"></li>
  <li data-color="FF3D7F"></li>
</ul>

<div class="image">IMAGE</div>