简体   繁体   中英

The color of and <input type=“color”> element on a page DOESN'T match its value attribute

I am working on a personnal exercise where I create a small app to allow users to update colors of different parts of an SVG using the <input type = "color"> element.

The SVG I am playing with is a simple cloud drawings with writing in it. You can modify 3 parts: cloud's stroke color, cloud's fill color and writing's color.

See it live:

  1. live : https://argonathmos.github.io/SVGfun/

  2. code: https://github.com/argonathmos/SVGfun

It is a simple UI with 3 areas:

  1. A Random button that applies random colors to each parts of the SVG.
  2. Three <input type="color"> element for each part of the SVG to modify each colors by hand.
  3. A Download button that allows the user to export the SVG with the custom colors applyied to it.

Here is what I notice that bothers me and don't know how to fix yet:

  • When I click "random", the SVG colors are updated, as well as the value of the <input type="color"> elements, as well as the color of the element on the page (ie the little squares color matches the colors of the associated SVG section).

  • When I apply a color individually through the <input type="color"> element the color of the SVG is updated as well as the value of the <input type="color"> element, and so is the color of the input color element on the page (the little square) .

  • But If I click "random" after having already selected a color from the color picker by hand: The SVG colors are updated, the value attribute of the <input type="color"> elements as well, but the color of the element on the page doesn't update its stays the same as the previously hand picked color. (ie the little square color DOESN'T match the color of the associated SVG section eventhough the value attribute of the element does.)

The problem appears to be, that you are using

 strokeColorInput.setAttribute('value',strokeColor);

to update the value of your color input fields. That is able to set the color for fields you did not already make an explicit choice in, but once you did, it doesn't work as expected any more.

(This is probably a manifestation of the well-known attribute vs property problem/issue here, see What is the difference between properties and attributes in HTML? )

Make that

 strokeColorInput.value = strokeColor;

instead, and it appears to be working fine.

Change strokeColorInput.setAttribute , fillColorInput.setAttribute , pathColorInput.setAttribute to:

strokeColorInput.value = strokeColor;
fillColorInput.value = fillColor;
pathColorInput.value = uniquePathcolor;

as you are updating HTML values. .setAttribute is for CSS attribute values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM