【问题标题】:Angular 4 scroll with arrow keys from text field to <li>Angular 4 使用箭头键从文本字段滚动到 <li>
【发布时间】:2018-02-13 15:04:19
【问题描述】:

我正在尝试实现类似 google 的搜索字段,我已经部分管理,但我无法工作的是箭头滚动的可能性。 我希望与他们的搜索字段一样,能够使用搜索字段中的箭头键滚动搜索结果列表:

到目前为止,我有以下内容:

    <div>
    <div class="searcher">
            <input name="term" #term class="ng-valid ng-touched" size="60"
              placeholder="Start typing something...." (keyup)="invokeAutoSuggest(term.value)" (click)="showElement = !showElement">
          <br/>
       </div>
       </div>
     <div id="autosuggestBox" class="autoSuggestGoogleLike" [hidden]="!showElement">
          <div class="autoSuggestDiv" *ngFor="let suggestion of suggestions" (click)="searchFromAutosuggest(suggestion.type,suggestion.value)" (click)="showElement = !showElement">
              {{suggestion.type}}:{{suggestion.value}}
            </div> 
       </div>

CSS:

.autoSuggestGoogleLike{
    border: 1px solid grey;
    width: 450px;
    height: 200px;
    position: relative;
    z-index:3;
    background-color : white;
    margin-left:-228px;
    position: absolute;
    left:50%;
    overflow: scroll;
}

所以searcher 是文本字段,autosuggestBox 是显示结果为列表的占位符,我希望能够单击searcher 文本字段中的向下箭头并访问结果。 有什么建议吗? 和div之间的关系有关系吗?

【问题讨论】:

  • 你可以尝试这样jsfiddle.net/6aj7t/23你可以编写一个自定义指令并将它放在你的父div上。即使你的jsfiddle使用jquery你也可以将它转换成普通的javascript

标签: html angular uitextfield angular2-template


【解决方案1】:

您必须首先在invokeAutoSuggest 函数中检查keyCode,以检测向上/向下按键,然后根据这些您可以增加/减少activeIndex。像这样……

在组件中

...
private activeIndex: number = 0;

public invokeAutoSuggest(ev: Event) {
   if (38 === ev.keyCode) {
     return this.prevActiveMatch();
   }
   if (40 === ev.keyCode) {
     return this.nextActiveMatch();
   }
   // your code ...
}
public nextActiveMatch() {
  this.activeIndex = this.activeIndex < this.list.length - 1 ? ++this.activeIndex : this.activeIndex;
}
public prevActiveMatch () {
  this.activeIndex = this.activeIndex > 0 ? --this.activeIndex : 0;
}
...

在模板中

    ...
    <div class="searcher">
      <input name="term" #term class="ng-valid ng-touched" size="60"
              placeholder="Start typing something...." (keyup)="invokeAutoSuggest($event)" (click)="showElement = !showElement">
    </div>
    ...
    <div class="autoSuggestDiv" *ngFor="let suggestion of suggestions; let i = index" (click)="searchFromAutosuggest(suggestion.type,suggestion.value)" (click)="showElement = !showElement" [ngClass]="{active: i===activeIndex}">
      {{suggestion.type}}:{{suggestion.value}}
    </div> 

...

查看选定的列表项

styles: [`
.active {
      background: blue;
      color: white;
    }
`]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-06
    • 2011-05-16
    • 2011-03-13
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多