Javascript 如何在Angular 4中聚焦和导航li元素?
我正在尝试在Angular 4中创建一个自定义Javascript 如何在Angular 4中聚焦和导航li元素?,javascript,html,css,angular,Javascript,Html,Css,Angular,我正在尝试在Angular 4中创建一个自定义选择选项。但是当集中在输入元素时,我不确定如何选择li选项 以下是我的html代码: 尽管渲染器添加了focus=“true”元素,但是li元素没有聚焦。我在聚焦时编写了css代码li背景色,但是元素没有聚焦,颜色也没有改变 另一个令我震惊的问题是如何使用键盘上下箭头导航li元素。在angular 4中,什么是有效的方法?我看到了,但不确定我该怎么做 请指导并帮助我解决这些问题。不要使用焦点,而是使用ngClass——如下所示: <input
选择选项。但是当集中在输入
元素时,我不确定如何选择li
选项
以下是我的html代码:
尽管渲染器添加了focus=“true”
元素,但是li
元素没有聚焦。我在聚焦时编写了css代码li背景色
,但是元素没有聚焦,颜色也没有改变
另一个令我震惊的问题是如何使用键盘上下箭头导航li
元素。在angular 4中,什么是有效的方法?我看到了,但不确定我该怎么做
请指导并帮助我解决这些问题。不要使用焦点,而是使用ngClass
——如下所示:
<input type="text" id="iLocation"
(focus)="onLocationFocus()"
(blur)="onLocationBlur()"
(keydown.ArrowUp)="onArrowUp()"
(keydown.ArrowDown)="onArrowDown()">
<span class="underline"></span>
<label for="iLocation">Preferred Type</label>
<div class="options-container">
<ul>
<li #item [ngClass]="{'focus-background': focusElement == item.tabIndex}"
*ngFor="let loc of locationOptions; let i = index" tabIndex="{{i}}">
{{loc.option}} </li>
</ul>
</div>
在组件类中:
locationOptions = [{ icon: 'school', option: 'School' }, { icon: 'home', option: 'Home' }];
public focusElement: number = -1;
constructor() { }
onLocationFocus() {
this.focusElement = 0;
}
onLocationBlur() {
this.focusElement = -1;
}
onArrowUp() {
if (this.focusElement > 0) {
this.focusElement--;
}
}
onArrowDown() {
if (this.focusElement <= this.locationOptions.length - 2) {
this.focusElement++;
}
}
locationOptions = [{ icon: 'school', option: 'School' }, { icon: 'home', option: 'Home' }];
public focusElement: number = -1;
constructor() { }
onLocationFocus() {
this.focusElement = 0;
}
onLocationBlur() {
this.focusElement = -1;
}
onArrowUp() {
if (this.focusElement > 0) {
this.focusElement--;
}
}
onArrowDown() {
if (this.focusElement <= this.locationOptions.length - 2) {
this.focusElement++;
}
}
<input type="text" id="iLocation"
(focus)="onLocationFocus()"
(blur)="onLocationBlur()"
(keydown.ArrowUp)="onArrowUp()"
(keydown.ArrowDown)="onArrowDown()">
<span class="underline"></span>
<label for="iLocation">Preferred Type</label>
<div class="options-container">
<ul>
<li #item [ngClass]="{'focus-background': focusElement == item.tabIndex}"
*ngFor="let loc of locationOptions; let i = index" tabIndex="{{i}}">
{{loc.option}} </li>
</ul>
</div>
.focus-background {
background-color: lightblue;
}