2013-04-20 106 views
1

在我的項目,我動態地添加li標籤ul元素,然後當焦點textarea元素上,我試圖生成每當用戶按下down arrow key第一li元件上的懸停效果。不知何故,我的努力沒有奏效。哈弗使用箭頭鍵

,我試過至今的代碼如下:

JS Fiddle

HTML

<textarea id="result" rows="4" cols="50"></textarea> 
<ul class="autoComplete"></ul> 

CSS

.autoComplete li { 
    background-color:#E1E1E1; 
    cursor: hand; 
    cursor: pointer; 
} 
.autoComplete li:hover { 
    background-color:#BDBDBD; 
} 

JS

var result = $('#result'); 
var autoComplete = $('.autoComplete'); 
result.keydown(function (event) { 
    if (event.keyCode == 40) { 
     if (autoComplete.children('li').length > 0) { 
      console.log('down'); 

      //should work with IE 
      autoComplete.children(":first").focus().hover(); 
     } 
    } 
}); 

PS:該解決方案應該是跨瀏覽(IE8 +)

+0

你爲什麼neeed鼠標事件?爲什麼不直接切換課程? – charlietfl 2013-04-20 12:24:11

+0

@charlietfl我在jQuery中並沒有那麼好。我希望你的意思是說arunPjohny在他的帖子中提到的。現在工作正常。 (雖然沒有在IE中檢查)。 – 2013-04-20 12:26:34

回答

2

嘗試

CSS

.autoComplete li { 
    background-color:#E1E1E1; 
    cursor: hand; 
    cursor: pointer; 
} 
.autoComplete li.hover { 
    background-color:#BDBDBD; 
} 

JS

var result = $('#result'); 
var autoComplete = $('.autoComplete'); 
result.keyup(function (event) { 
    console.log('keydown'); 
    if (event.keyCode == 40) { 
     if (autoComplete.children('li').length > 0) { 
      console.log('down'); 

      //should work with IE 
      autoComplete.children(":first").mouseenter(); 
     } 
    } 
}); 

autoComplete.on('mouseenter', 'li', function(){ 
    $(this).addClass('hover'); 
}).on('mouseleave', 'li', function(){ 
    $(this).removeClass('hover'); 
}); 

演示:Fiddle

+0

嗨,你的解決方案工作正常。但是剛纔我意識到焦點仍在textarea上,儘管懸停在'li'元素上,即使滾動條也不會下降。請檢查此[鏈接](http://jsfiddle.net/gb6Ws/4/)以獲得更好的理解。 – 2013-04-20 14:15:46