Open browser-standard colorpicker with javascript

2020-07-22 17:11发布

问题:

Does anyone knows a javascript only way to open the browser-standard colorpicker, without using a html field? so i want a javascript what does exactly the same a a click on the html input color field. Bart

回答1:

You are going to have to use the input field, you can just hide it off the page. Issue here is the fact that the color dialog requires a click in browsers in order to open up the color dialog. It will not work if you just call click()

document.getElementById("xxx").addEventListener("click", function() {
  document.getElementById("c").focus();
  document.getElementById("c").value = "#FFCC00";
  document.getElementById("c").click();
});
.hidden {
  position: absolute;
  left: -10000px;
  top: auto;
  width: 1px;
  height: 1px;
  overflow: hidden;
}
<input type="color" id="c" tabindex=-1 class="hidden">
<input type="button" id="xxx" value="Click Me!">



回答2:

Here's a good old "hover-hack" solution that works even in MS Edge:

<input type="color" style='opacity:0;width:100px;position:absolute;'/>
<button>clickme</button>

then bind onchange to the colro element

https://jsfiddle.net/Lnzm0sry/2/