Javascript 如何使用键盘事件模拟悬停

Javascript 如何使用键盘事件模拟悬停,javascript,jquery,css,angular,typescript,Javascript,Jquery,Css,Angular,Typescript,我有以下HTML模板,其中列表项被动态添加到下拉列表中 <button class="btn btn-default btn-sm dropdown" (keydown)="triggerTraverse($event)"></button> <fa-list-filler> <li *ngFor="let item of items [class.active]="checkItem(item,selectedItem)">

我有以下HTML模板,其中列表项被动态添加到下拉列表中

<button class="btn btn-default btn-sm dropdown" (keydown)="triggerTraverse($event)"></button>
    <fa-list-filler>
        <li *ngFor="let item of items [class.active]="checkItem(item,selectedItem)">
            <span (click)="doNavigate()" class="cookie"></span>
        </li>
    </fa-list-filler>
当我用鼠标悬停这些列表项时,我可以看到应用于列表项的悬停样式,即,在本例中,我可以看到黄色背景色

默认情况下,第一个项目处于选中状态,即它的类处于活动状态。然后,当用户按下向下箭头键时,活动类保持在同一位置,但悬停状态应向下移动到下一个列表项,然后移动到下一个列表项,并应环绕

我实现了以下方法,但无法正确处理后续元素

triggerTraverse(evt: KeyboardEvent){
   if(evt.keyCode === 27){
    closeDropdown();
}else if(evt.keyCode === 40){
    let initialEle = document.querySelector('li.active');
initialEle.nextElementSibling.firstElementChild.classList.add('hoverstyle');
}
}
hoverstyle是我刚刚实现的另一个类,用于将backgroundcolor添加到元素中

.hoverstyle{
 background-color: 'pink';
}

请任何人帮忙。

跟踪所选索引并使用
ngClass
指令

例如:

模板:

<input ... (keydown)="onKeydown($event)">
<div *ngFor="let option of options; let i = index;"
     (mouseover)="highlight(i)"
     [ngClass]="{'selected': i === selectedIndex}">
    <span>{{ option }}</span>
</div>

您是否看到添加到inspect元素中的
li
中的类
hoverstyle
?是的。但这只发生在第二个元素上,因为我没有做任何进一步的事情来遍历整个列表。Kul,回答这个问题,如果逻辑说从
li开始。活动
(ur第一个元素),然后向下移动,它实际上会超出第二个元素吗?不,不会!在这种情况下,它只是卡在第二个元素上!这正是重点。在当前逻辑中,它总是从最上面的元素li.active开始。所以每次你按下向下键,下一个元素总是第二个元素。不过我面临一个问题,当下拉列表中有很多元素时,当我用向下或向上箭头遍历列表时,这些元素就看不到了。我怎样才能做到这一点?有什么提示吗?这很有效@ViewChild(“滚动”)滚动:ElementRef;ngAfterViewInit():void{this.scroll.nativeElement.scrollIntoView(false);}
<input ... (keydown)="onKeydown($event)">
<div *ngFor="let option of options; let i = index;"
     (mouseover)="highlight(i)"
     [ngClass]="{'selected': i === selectedIndex}">
    <span>{{ option }}</span>
</div>
selectedIndex = 0

...

highlight(i: number) {
    this.selectedIndex = i;
}

onKeydown(event: KeyboardEvent) {
    if (event.code === 'ArrowUp' && this.selectedIndex > 0) {
        event.preventDefault();
        this.selectedIndex--;
    } else if (event.code === 'ArrowDown' && this.selectedIndex < (this.options.length - 1)) {
        event.preventDefault();
        this.selectedIndex++;
    } 
}
.selected {
    background-color: red;
}