当焦点事件在输入上触发时,使HTML5 datalist可见 [英] Making HTML5 datalist visible when focus event fires on input

查看:881
本文介绍了当焦点事件在输入上触发时,使HTML5 datalist可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些人可能已经知道造型选择元素是一场噩梦,如果没有一些javascript技巧,几乎是不可能的。 HTML5中的新数据列表可以用于相同的目的,因为向用户显示选项列表,并且值记录在输入文本字段中。

As some might know already styling select element is a nightmare, literally impossible without some javascript trickery. The new datalist in HTML5 could serve the same purpose since the user is presented with a list of options and the value is recorded in an input text field.

此处的限制是,在用户开始在文本字段中输入内容之前,列表不会出现,即使这样,也只会根据输入显示可能的匹配项。我想要的行为是,一旦焦点在该字段上,整个选项列表就变得可见。

The limitation here is the list does not appear until the user start typing something in the text field and even then is only shown possible matches based on their input. The behavior I want is that as soon as there is focus on the field the entire list of options become visible.

所以我有这个代码 - 查看jsbin

So I have this code - view on jsbin

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Input - Datalist</title>
</head>
<body>
  <input list="categories">
  <datalist id="categories">
    <option value="Breakfast">Breakfast</option>
    <option value="Brunch">Brunch</option>
    <option value="Lunch">Lunch</option>
    <option value="Dinner">Dinner</option>
    <option value="Desserts">Desserts</option>
  </datalist>
</body>
</html>

我试图用这个Javascript显示:

and I'm trying to get that to show with this Javascript:

    var catVal = document.getElementsByTagName("input")[0],
    cat = document.getElementById("categories");

    catVal.style.fontSize = "1.3em";

    catVal.addEventListener("focus", function(event){
     cat.style.display = "block";
    }, false);

任何帮助都将不胜感激,

Any help would be appreciated,

干杯

推荐答案

我使用以下代码:

<input name="anrede" 
    list="anrede" value="Herr" 
    onmouseover="focus();old = value;" 
    onmousedown = "value = '';" 
    onmouseup="value = old;"/>

<datalist id="anrede">
    <option value="Herr" selected></option>
    <option value="Frau"></option>
    <option value="Fraulein"></option>
</datalist>

mouseover:

设置焦点并记住旧的a - global - variable中的值

mouseover:
Set focus and memorize old value in a -- g l o b a l -- variable

mousedown:

删除值并显示 datalist (内置功能)

mouseup:

恢复旧值

mouseup:
Restore old value

然后选择新值。

为组合框找到一个可接受的解决方法。

Find this an acceptable workaround towards a combobox.

这篇关于当焦点事件在输入上触发时,使HTML5 datalist可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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