【问题标题】:ionBlur Event: Detect the element that is receiving the focusionBlur 事件:检测正在接收焦点的元素
【发布时间】:2019-02-02 01:45:40
【问题描述】:

通过自定义指令,我想确定发生模糊事件时接收焦点的元素是什么:

@Directive({
  selector: '[my-directive]',
  host: {
    //...
    '(ionBlur)': 'onBlur($event)'
  }
})
export class MyCustomDirective implements OnInit {
    //...
    onBlur($event) {
        console.log(event) // This logs a CustomEvent that contains information only about the element that losing the focus
        console.log(event.relatedTarget) // This logs undefined
    }
    //...
}

我将此指令与 ion-input 元素一起使用:

<ion-input my-directive></ion-input>

测试时,onBlur方法的event参数包含targetcurrentTarget这两个属性都是失去焦点的元素,但是event.relatedTarget未定义:

是否可以让元素也获得焦点?

【问题讨论】:

  • 也许relatedTarget 属性是您正在寻找的(参见this answer)。
  • 感谢您的提议。不幸的是,event.relatedTarget 的结果是未定义的。我编辑了我的问题以提及它

标签: angular ionic-framework


【解决方案1】:

Ionic 5.3 终于added this feature.

您现在可以通过ionBlurEvent.detail.relatedTarget 访问获得焦点的元素。

请注意,ionBlurEvent.detail 包含“原始”HTML FocusEvent

还要注意FocusEvent.relatedTarget 可能仍然为空——以防没有“可聚焦”元素获得焦点。另见:blur event.relatedTarget returns null

【讨论】:

    【解决方案2】:

    首先,您需要一个 Hostlistener 来监视模糊事件。 当您使用 HostListener 捕获模糊事件时:

      @HostListener('ionBlur', ['$event'])
      onBlur($event: FocusEvent) {
        console.log(event)
      }
    

    可以看到relatedTarget可用

    但是

        console.log(event.relatedTaget)
    

    会产生编译错误。

    因为它是一个 JSON 结构,所以我建议这样做:

    console.log(event['relatedTarget'])
    

    然后你会得到这个:

    Demo

    【讨论】:

    • 我认为blur 事件没有被考虑在内,因为当元素失去焦点时它不会被触发。在我的 Ionic 应用程序中,我需要使用 ionBlur 事件,正如我在问题中提到的,$event 参数是 CustomEvent 的一个实例,relatedTarget 属性甚至不存在。我将编辑我的问题以添加记录事件的屏幕截图
    • 感谢您的示例。不幸的是,当我使用ion-input 元素而不是input 元素时,不会触发blur 事件。从ion-input 失去焦点时触发的唯一事件是ionBlur,使用它时,relatedTarget 属性未定义
    • 再次感谢您更新示例 :) 我在我的应用程序中遵循了相同的代码,但它仍然无法正常工作。我注意到您的 stackblitz 示例和我的应用程序之间的区别在于,我使用的是 ionic-angular 版本 4.0.0,而示例中使用的版本是 3.9.2
    • 最新的 ionic-angular 版本不是 3.9.3 吗? npmjs.com/package/ionic-angular
    • 我的错,不是 ionic-angular,而是 4.0.0 关联到 @ionic/angular:npmjs.com/package/@ionic/angular
    【解决方案3】:

    我正在使用 Ionic 4,对我来说效果最好:

    onFocusLostEvent() {
        let input = event['target'] as HTMLElement;
        console.log(input.id); // the id of the ion-input object for its identification
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      相关资源
      最近更新 更多