想要的效果是 一個輸入框, 輸入內容按回車鍵 后 ,
下方彈出一個表格, 表格上的資料,可以用上下鍵 上下移動選擇,
表格內資料按下回車鍵,觸發一個 js事件
uj5u.com熱心網友回復:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<input type="text" value="" id="search"/>
<ul class="list" tabindex="0"></ul>
<div>當前選擇: <span id="txt"></span></div>
<style>
#search {
width: 150px;
}
ul {
margin: 0;
padding: 0;
outline: none;
list-style: none;
width: 150px;
border: 1px #f4f4f4 solid;
}
ul li {
text-align: center;
line-height: 28px;
border-bottom: 1px #f4fff4 solid;
}
ul li:last-child {
border-bottom: none;
}
.active {
color: #fff;
background: lightgray;
}
</style>
<script>
var list = ['a1','b1','aaa','aa2','cc4','dd4','b2','c3','b3']
var result = []
$('#search').on('keydown', function(e) {
if (e.keyCode == 13) {
var val = $(this).val()
// 不為空繼續
if (!val) return
result = list.filter(item => item.indexOf(val) > -1)
createList()
}
})
function createList() {
let arr = []
result.forEach(item => {
// 其他屬性可以加到dom上
arr.push(`<li>${item}</li>`)
})
$('.list').html(arr.join(' '))
$('.list').focus()
$('.list li').eq(0).addClass('active')
$('#txt').html($('.list li').eq(0).text())
}
$('.list').on('keydown', function(e) {
var el = $('li.active'),
index = el.index()
if (e.keyCode == 13) {
// 回車事件,需要其他屬性自己獲取
$('#txt').html(el.text())
} else if (e.keyCode == 38) {
// 上鍵
if (el.prev('li').length>0) {
el.removeClass('active').prev('li').addClass('active')
$('#txt').html(el.prev('li').text())
}
} else if (e.keyCode == 40) {
// 下鍵
if (el.next('li').length > 0) {
el.removeClass('active').next('li').addClass('active')
$('#txt').html(el.next('li').text())
}
}
})
</script>
要表格就把ul替換成table,按鍵操作就使用li換成 tr
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/92682.html
標籤:HTML(CSS)
