触发html5输入datalist下拉列表以显示

时间:2015-01-17 02:42:14

标签: javascript html5

<input>中具有预定义值的HTML5 <datalist>元素中,当用户输入匹配值或点击 down 键时,下拉列表会显示

有没有办法触发此下拉列表显示?我可能会在Angular中动态更改datalist,因此希望能够触发此列表的显示。

  <input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>

1 个答案:

答案 0 :(得分:0)

是的,我们可以:

&#13;
&#13;
	var keyboardEvent = document.createEvent("KeyboardEvent");
	var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


	keyboardEvent[initMethod](
					   "keyup", // event type : keydown, keyup, keypress
						true, // bubbles
						true, // cancelable
						window, // viewArg: should be window
						false, // ctrlKeyArg
						false, // altKeyArg
						false, // shiftKeyArg
						false, // metaKeyArg
						40, // keyCodeArg : unsigned long the virtual key code, else 0
						0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
	);
	document.getElementById("test").focus();
	document.getElementById("test").dispatchEvent(keyboardEvent);
&#13;
  <input id="test" list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
&#13;
&#13;
&#13;

使用dispatchEventcreateEvent。受IE9 +,Chrome和FF支持。