Datalist字序

时间:2015-07-04 13:44:05

标签: javascript html5 html-datalist

假设您有一个简单的输入字段,并附有数据列表。

<input list="suggestions>
<datalist id="suggestions">
   <option value="Apple Pie"></option>
   <option value="Strawberry Cake"></option>
</datalist>

输入“Apple Pie”时,提示会按预期显示。但是,当我将输入字段中的文本更改为“Pie Apple”时,没有显示任何内容。

每当我以不同的顺序输入单词时,有没有办法让它显示Apple Pie选项?

1 个答案:

答案 0 :(得分:1)

这是一个纯JavaScript解决方案,它使用datalist元素模拟select功能。

var inp= document.querySelector('input'),
    sel= document.querySelector('select');

inp.addEventListener('input', change);
inp.addEventListener('focus', change);
inp.addEventListener('blur', function() {this.value= sel.value;});
sel.addEventListener('change', function() {inp.value= this.value;});

inp.addEventListener('keydown', function(e) {
  if(e.which === 40) {  //down arrow
    sel.selectedIndex = Math.min(sel.selectedIndex+1, sel.options.length-1);
    this.value= sel.value;
  }
  else if(e.which === 38) { //up arrow
    sel.selectedIndex = Math.max(sel.selectedIndex-1, 0);
    this.value= sel.value;
  }
});

function change() {
  var options= ['Apple Pie', 'Apple Streudel', 'Blackberry Cobbler', 'Strawberry Cake', 'Banana Pudding'],
      words= inp.value.toLowerCase().trim().split(' '),
      match,
      s= '';

  options.forEach(function(o) {
    match= true;
    words.forEach(function(w) {
      if(w > '' && 
         o.toLowerCase().indexOf(w) !== 0 && 
         o.toLowerCase().indexOf(' '+w) === -1) {
        match= false;
      }
    });
    if(match) {
      s+= '<option>'+o;
    }
  });
  sel.innerHTML= s;
  sel.size= sel.options.length;
}

inp.focus();
input, select {
  display: block;
  width: 200px;
  border: 1px solid silver;
  box-sizing: border-box;
  font: 13px arial;\
}

input:focus + select, select:focus {
  display: block;
}

select {
  display: none;
}
<input type="text">
<select></select>