在颜色选择器的多个实例内输入文本

时间:2017-04-30 14:43:15

标签: javascript

我试图创建一个带有文本输入的颜色选择器的多个实例。

注释代码适用于单个实例,但我不确定如何使用多个实例。这是我的最大努力..

https://jsfiddle.net/ogj5ynak/6/



/*
 * Text input in multiple instance
*/
var target = document.querySelectorAll('.colorpicker');

var x = [];

for (var i = 0, len = target.length; i < len; i++) {

  var picker = new CP(target[i]);

  x[i] = document.createElement('input');
  x[i].type = 'text';

  var control = picker.picker.querySelector('.color-picker-control');
  control.appendChild(x[i]);

  x[i].oncut = pickerUpdate;
  x[i].oninput = pickerUpdate;
  x[i].onkeyup = pickerUpdate;
  x[i].onpaste = pickerUpdate;

  picker.on('change', function (color) {
    //x[i].value = '#' + color;
    this.target.value = '#' + color;
    this.target.style.backgroundColor = '#' + color;
  });

  function pickerUpdate () {
    picker.set(this.value);
    picker.picker.value = '#' + this.value;
  }
}
&#13;
<link href="https://tovic.github.io/color-picker/color-picker.min.css" rel="stylesheet"/>
<script src="https://recently.appifiny.io/content/script/lib.js"></script>
<input type="text" class="colorpicker">
<input type="text" class="colorpicker">
<input type="text" class="colorpicker">
<input type="text" class="colorpicker">
<input type="text" class="colorpicker">
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您的问题是i事件中change的范围。

您可以解决保存索引的问题:

picker.myprop = i;

获取已保存的索引:

picker.on('change', function (color) {

    var i = this.myprop; // HERE !

    x[i].value = '#' + color;
    this.target.value = '#' + color;

    this.target.style.backgroundColor = '#' + color;
    //app.settings[this.target.getAttribute('name')] = color;
});

Try it on JSFiddle