使用向上和向下箭头键使用javascript访问Div内容
-
03-07-2019 - |
题
我有一个Div标签,其中包含4个子Div标签
<Div id="Parent">
<div id="childOne">ChildOne </div>
<div id="childOne">ChildTwo </div>
<div id="childOne">ChildThree </div>
<div id="childOne">ChildFour </div>
</Div>
现在我想通过Javascript使用向上和向下箭头键访问这些Child Div 上面的div是在单击TextBox时显示的。我希望用户可以选择任何子div,其选中的值出现在TextBox中。我通过附件onClick事件为每个childDiv实现了最终结果。
解决方案
您是否正在寻找所谓的自动完成或建议?
其他提示
这是一个免费的图书馆解决方案,可以帮助您入门。
您可能希望在文本框获得或失去焦点时添加隐藏和显示div的事件。也许[esc]应该清除选择? (我没有在ie中测试过它)
<style>div.active{ background: red }</style>
<input type="text" id="tb">
<div id="Parent">
<div id="childOne">ChildOne </div>
<div id="childOne">ChildTwo </div>
<div id="childOne">ChildThree </div>
<div id="childOne">ChildFour </div>
</div>
<script type="text/javascript">
function autocomplete( textBoxId, containerDivId ) {
var ac = this;
this.textbox = document.getElementById(textBoxId);
this.div = document.getElementById(containerDivId);
this.list = this.div.getElementsByTagName('div');
this.pointer = null;
this.textbox.onkeydown = function( e ) {
e = e || window.event;
switch( e.keyCode ) {
case 38: //up
ac.selectDiv(-1);
break;
case 40: //down
ac.selectDiv(1);
break;
}
}
this.selectDiv = function( inc ) {
if( this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length ) {
this.list[this.pointer].className = '';
this.pointer += inc;
this.list[this.pointer].className = 'active';
this.textbox.value = this.list[this.pointer].innerHTML;
}
if( this.pointer === null ) {
this.pointer = 0;
this.list[this.pointer].className = 'active';
this.textbox.value = this.list[this.pointer].innerHTML;
}
}
}
new autocomplete( 'tb', 'Parent' );
</script>
你的意思是“用箭头键访问它们”?每个div中都有文本...它们不包含任何交互元素,因此键盘在这里没有相关性。也许你需要详细说明你的问题?
不隶属于 StackOverflow