触发html5输入数据列表下拉菜单以显示 [英] Trigger html5 input datalist dropdown to show up

查看:112
本文介绍了触发html5输入数据列表下拉菜单以显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In an HTML5 <input> element with pre-defined values in a <datalist>, when user either enters a matching value or hits the down key, the dropdown list shows up.

有没有一种方法可以触发此下拉列表显示?我可能会在Angular中动态更改datalist,因此希望有一种方法可以触发此列表的显示.

Is there a way to trigger this dropdown list to show up? I might change the datalist dynamically in Angular, and so would like to have a way to trigger the showing up of this list.

  <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>

推荐答案

是的,我们可以:

	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);

  <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>

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

Using dispatchEvent and createEvent. Supported by IE9+, Chrome and FF.

这篇关于触发html5输入数据列表下拉菜单以显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆