HTML 输入自动填充占位符

HTML input autofill placeholder

当用户写入文本框时显示用户建议的最佳方法是什么?我在 JS 数组中有所有可能的值。以数组["TYPO3", "Javascript"]为例。现在如果用户输入这样一个字符串的起始字符,他应该得到这样的建议:

我很清楚 placeholder html5 tag, but this would work only if the textbox is empty. I also know of the Datalist element or jQuery autocomplete 但这些只允许特定值。我还想要我的文本框中没有预定义的内容。

我的想法是在光标之后添加一个 <span> 标签,在输入 keyup 事件时更改其内容并将范围移动到光标当前所在的位置。这也使我可以设置建议文本的样式。

但对我来说这似乎是一个糟糕的 hack,那么有没有更干净的解决方案?

我不能告诉你什么是最好的方法,但如果你相信Google的方法,那么他们的解决方案就很简单:

  • 有一个用于实际输入的常规文本框 (<input type='text' ...>)。
  • 兄弟 <input> 元素是 disabled

实际的文本框应该在禁用的文本框之上。 当用户开始输入并且您找到了自动完成的匹配项时,建议的文本应成为另一个 disabled 输入元素的 value(建议的文本应为银色)。

这是一个小例子:https://jsfiddle.net/e3L93o7g/

这就是你想要的(我希望):

编辑: 不知何故它不能在这里正常工作,所以我把 public jsfiddle 作为备份 :).

const names = [
 'Predator_1', 'Semantic_RL', 'Thorn', 'Kill_09', 'One', 'Preclude'
];

const container = document.querySelector('#autocomplete-container');
const autocomplete = container.querySelector('#autocomplete');
const mainInput = container.querySelector('#main-input');

mainInput.addEventListener('keyup', onKeyUp, false);

let foundName = '';

function onKeyUp(e) {
 // e.preventDefault();
 console.log( mainInput.value, e );
  console.log( autocomplete.textContent );
  
  if (mainInput.value === '') {
   autocomplete.textContent = '';
    return;
  }
  
  if  (keyChecker(e, 'Enter') || keyChecker(e, 'ArrowRight') ) {
   console.log('keyChecker')
  mainInput.value = foundName;
    autocomplete.textContent = '';
  }
  
  let found=false;
  
  for (let word of names) {
   if (word.indexOf(mainInput.value) === 0) {
     foundName = word;
     autocomplete.textContent = word;
      break;
    } else {
     foundName = '';
      autocomplete.textContent = '';
    }
  }
  
}

function keyChecker(e, key) {
 const keys = {
   'ArrowRight':37,
    'Enter':13,
    'ArrowLeft':39
  }
  
 if (e.keyCode === keys[key] || e.which === keys[key] || e.key === key) return true;
  
  return false;
}
div#autocomplete-container, input#main-input {
  font: 14px Tahoma, Verdana, Arial, sans-serif;
}

#autocomplete-container {
  position: relative;
  box-sizing: border-box;
  width: 300px;
  height: 32px;
  line-height: 32px;
  margin: 0 auto;
}

#autocomplete {
  width: 300px;
  position: absolute;
  top: 0;
  left: 0;
  padding: 0 8px;
  line-height: 32px;
  box-sizing: border-box;
  height: 32px;
  color: #999;
  cursor: text;
}

#autocomplete-container input[type=text] {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  height: 32px;
  line-height: 32px;
  border: 1px solid #aaa;
  border-radius: 4px;
  outline: none;
  padding: 0 8px;
  box-sizing: border-box;
  transition: 0.2s;
  background-color: transparent;
  cursor: text;
}

#autocomplete-container input[type=text]:focus {
  border-color: dodgerBlue;
  box-shadow: 0 0 8px 0 dodgerBlue;
}
<div id="autocomplete-container">
  <div id="autocomplete"></div>
  <input
    id="main-input" 
    type="text"
    placeholder="Enter route..." /> 
</div>