最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - <input type="color" > — open colorpicker with js - Stack Overflow

programmeradmin1浏览0评论

I have got that:

<span class="opener">Open</span>
<input type="color" class="btn-invisible" />

and I would like to open the colorpicker of that field using JS. I have tried:

document.querySelector('span.opener')
  .addEventListener('click', 
    e => document.querySelector('.btn-invisible').focus()
  );

But that doesn't open the color picker. If that can be done by JS, how?

I have got that:

<span class="opener">Open</span>
<input type="color" class="btn-invisible" />

and I would like to open the colorpicker of that field using JS. I have tried:

document.querySelector('span.opener')
  .addEventListener('click', 
    e => document.querySelector('.btn-invisible').focus()
  );

But that doesn't open the color picker. If that can be done by JS, how?

Share Improve this question asked Apr 24, 2017 at 14:05 philippphilipp 16.5k15 gold badges65 silver badges118 bronze badges 2
  • 3 Why .focus() instead of .click()? – Sebastian Simon Commented Apr 24, 2017 at 14:06
  • 1 Possible duplicate of Open browser-standard colorpicker with javascript without type=color – Yury Tarabanko Commented Apr 24, 2017 at 14:08
Add a ment  | 

3 Answers 3

Reset to default 8

There's no need for javascript, just wrap a label around the input:

<label>
  Open
  <input type="color" style="display:none">
</label>

The color input control requires a click (like a button).

document.querySelector('span.opener')
  .addEventListener('click', 
    e => document.querySelector('.btn-invisible').click()
  );
.btn-invisible {
   display: none;
}
<span class="opener">Open</span>
<input type="color" class="btn-invisible" />

Add an Id to the color input (you can keep it hidden if you want) then fire a click event with javascript. Click outside the color picker to get the color value.

function show_colorpicker(){
document.getElementById('pick_color').click();
}
function show_color(){ alert(document.getElementById('pick_color').value)
}
<input onchange="show_color();" type="color" id="pick_color" name="pick_color" style="display:none" />

<a onclick="show_colorpicker();">Click me!</a>

发布评论

评论列表(0)

  1. 暂无评论