[英]How to add css class to li on keypress
我在每個li中都有單個字符的無序列表。 如果用戶按下鍵盤上的任何字母,我想將CSS類添加到頁面上相應的li上。 如果用戶按下鍵盤上的A,我想查找以A為內容的li並向其中添加css類
<div>
<ul class ='list'>
<li>a</li>
<li>b</li>
<li>c</li>
...
<li>z</li>
</ul>
</div>
這就是我開始的方式
$(document).keypress(function(e){
var x = e.which;
if((x >= 65 && x <= 90)||(x >=97 && x <= 122)||(x >=48 && x <= 57)) {
checkfirst(x);
}
});
// pick list item with the text content of the value passed
function checkfirst(x){
var y = $('.list').find('li');
// code will go here
//am trying to find the li with text equal to the argument passed
}
不要使用按鍵,而要使用按鍵。 有關詳細信息,請閱讀此文章關鍵事件差異 。
我創建了一個函數,當在文檔上按下的字符與菜單行的內容相對應時,添加一個活動類。
$(document).on('keyup', function(e) { if (e.shiftKey == false && e.ctrlKey == false) { // get the character typed var charTyped = String.fromCharCode(e.which); // remove style active from all li with no child and add this to the elements with the // content matching the character typed $('div ul.list li:not(:has(*))').removeClass('active').filter(function() { return this.textContent.toUpperCase() == charTyped; }).addClass('active'); } });
.list { font-family: Verdana, sans-serif; font-size: 12px; margin: 0; padding: 0; list-style: none; } .list li { background: yellowgreen; display: block; width: 150px; height: 30px; margin: 2px 0; font-size: large; } .active { background-color: #54BAE2 !important; }
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <div> <ul class ='list'> <li>a</li> <li>b</li> <li>c</li> ... <li>z</li> </ul> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.