【问题标题】:How to unselect input content when focus on it by pushing tab key?如何通过按 Tab 键取消选择输入内容?
【发布时间】:2020-10-24 00:31:49
【问题描述】:

在 html 表单中, 当您使用选项卡进行下一个输入时,默认情况下会选择所有内容, 如何取消选中?

【问题讨论】:

    标签: html angular typescript input unselect


    【解决方案1】:

    只需在焦点事件上将target.selectionEnd 设置为 0

    <input (focus)="unselectOnFocus($event)">
    
    unselectOnFocus(event: Event): void {
      event.target.selectionEnd = 0;
    }
    

    【讨论】:

      【解决方案2】:

      设置#myInput并绑定焦点事件 &lt;input #myInput (focus)="onFocus()"&gt;

      @ViewChild('myInput') myInput: ElementRef<HTMLInputElement>;
      

      onFocus() {
          setTimeout(() => {
            this.myInput.nativeElement.setSelectionRange(0,0);
          }, 0)
      }
      

      超时是必需的,因为当您使用 Tab 键选择输入时,文本会在焦点事件之后立即自动选择。

      【讨论】:

        【解决方案3】:

        要将元素设置为不可选择,您可以在输入元素中使用tabindex = -1 属性,如下所示-

        &lt;input tabindex='-1'&gt;

        负值(通常是 tabindex="-1")表示该元素无法通过顺序键盘导航访问,但可以通过 Javascript 或通过鼠标点击来获得焦点。

        您可以在此处查看更多信息-tabindex MDN guide

        希望这会对你有所帮助。

        【讨论】:

          猜你喜欢
          • 2011-08-17
          • 1970-01-01
          • 2012-06-24
          • 2015-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多