[英]Auto select in a Bootstrap dropdown
假設我有一個簡單的html select
標記。 如果我單擊選擇框並開始鍵入項目的第一個字母,那么該項目將在我鍵入時自動選擇。
我想為Bootstrap下拉菜單提供相同的功能。 現在,它不響應用戶鍵入的任何字母。 如何添加像select
標簽一樣的自動選擇?
以下是Bootply的一個示例: http : //www.bootply.com/126297 。
您需要將類form-control
添加到select中。 我編輯了你的Bootply,雖然select的樣式看起來不正確,但select會按你喜歡的方式運行。 創建表單時,請務必遵循所有Bootstrap文檔 。
<div>
<select class="form-control">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<div></div>
</div>
你可以使用jQuery附加按鍵處理程序下拉時shown
。 然后查看li
項目以查看第一個字母是否與按下的鍵匹配...
$('#cars').on('shown.bs.dropdown', function () {
var $this = $(this);
// attach key listener when dropdown is shown
$(document).keypress(function(e){
// get the key that was pressed
var key = String.fromCharCode(e.which);
// look at all of the items to find a first char match
$this.find("li").each(function(idx,item){
$(item).removeClass("active"); // clear previous active item
if ($(item).text().charAt(0).toLowerCase() == key) {
// set the item to selected (active)
$(item).addClass("active");
}
});
});
})
工作演示: http : //www.bootply.com/126541
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.