Created
January 18, 2014 07:21
-
-
Save caok/8487368 to your computer and use it in GitHub Desktop.
键盘上下键头选中div的内容
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>SimulateUpDownKeySelect</title> | |
</head> | |
<body> | |
<input type="text" id="txtInput"/> | |
<div id="divSelect"> | |
<li>123</li> | |
<li>456</li> | |
<li>abc</li> | |
<li>def</li> | |
<li>zzz</li> | |
</div> | |
</body> | |
<script type="text/javascript"> | |
function $(sId) | |
{ | |
return document.getElementById(sId); | |
} | |
function clearSelectedOptBgColor(target) | |
{ | |
if (target.seletedIndex >= 0) | |
target.options[target.seletedIndex].style.backgroundColor = ""; | |
} | |
function setSelectedOptBgColor(target) | |
{ | |
target.options[target.seletedIndex].style.backgroundColor = "yellow"; | |
} | |
var upKeyCode = 38; | |
var downKeyCode = 40; | |
var enterKeyCode = 13; | |
var oInput = $("txtInput"); | |
oInput.options = $("divSelect").getElementsByTagName("li"); | |
oInput.seletedIndex = -1; | |
oInput.focus(); | |
oInput.onkeyup = function(event){ | |
if (event == undefined) | |
event = window.event; | |
switch (event.keyCode) | |
{ | |
case upKeyCode: | |
clearSelectedOptBgColor(this); | |
this.seletedIndex--; | |
if (this.seletedIndex < 0) | |
this.seletedIndex = this.options.length - 1; | |
setSelectedOptBgColor(this); | |
break; | |
case downKeyCode: | |
clearSelectedOptBgColor(this); | |
this.seletedIndex++; | |
if (this.seletedIndex >= this.options.length) | |
this.seletedIndex = 0; | |
setSelectedOptBgColor(this); | |
break; | |
case enterKeyCode: | |
this.value = this.options[this.seletedIndex].innerHTML; | |
break; | |
} | |
}; | |
oInput.onblur = function(){ | |
clearSelectedOptBgColor(this); | |
this.seletedIndex = -1; | |
}; | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment