开发者

using the arrow key in a div

I have two divs. One of them contains an input field the other a list of suggestions. What I would like is the ability for the user to come down in the second div with the use of the arrow key an also scroll through the list of suggestions. This is how it looks:

<div id="first"><input type="text" /></div>

<div id="second"> 
<ul>
<li>suggestion</li>
<li>suggestion2</li>
<li>suggestion3</li>
</ul>
</div>

I actualy found something here at Stack: Fiddle

But I开发者_开发百科 can't make it work because it uses class names and I'm using ID's instead. I would very much appreciate if someone would rewrite this for me so I can append ID's.


It was a pretty simple change to get that fiddle to work how you wanted it:

jsfiddle

The class names were only there to highlight the selected item. The fiddle uses id's to reference the input and items wrapper. It wasn't much different than your code really. Now that you can see it working with your code you should be able to make and additional changes you see fit. Hope it helps.

EDIT: Woops. Looks like I forgot to update the fiddle. This has been fixed.


Use the onKeyDown event like

function KeyDownEvent(Event)
{
    if (Event.keyCode == 40) // down key was pressed 
    else if (Event.keyCode == 38) // up key was pressed
}

document.getElementById("textinput").onkeydown = KeyDownEvent;

Then your input HTML would look like:

<input type="text" id="textinput" />

Note that my example does not make use of the often unnecessary jQuery library.

In the actual events you would then change the style of the list items and save which value was selected by the user for autocompletion, which you should be able to figure out for yourself now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜