2013-04-20 103 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