简体   繁体   English

模糊输入而不调用 Blur() function

[英]Blur input without calling Blur() function

I have angular custom input element.我有 angular 自定义输入元素。 Now what I want to do is to blur this input programmatically using javascript.现在我想做的是使用 javascript 以编程方式模糊这个输入。 My special case is that I don't want to touch input itself.我的特殊情况是我不想触摸输入本身。 For instance, when I click some other document element on screen, input blurs, but when I call click() function on this dom element, it doesn't.例如,当我单击屏幕上的其他文档元素时,输入模糊,但是当我在此 dom 元素上调用 click() function 时,它不会。 So how can I blur it without touching input?那么如何在不触摸输入的情况下模糊它呢?

To be able to blur your input without touching it, you need to focus an other element.为了能够在不触摸输入的情况下模糊输入,您需要关注其他元素。

One could think that simply calling focus() on the default document.activeElement ( <body> ) would do, but it doesn't... Browsers all differ on this, and that's one part of the specs I still struggle a lot to get my head off.有人可能会认为只需在默认document.activeElement ( <body> ) 上调用focus()就可以了,但事实并非如此……浏览器对此各不相同,这是规范的一部分,我仍然很难做到把我的头拿下来。

What all browsers agree on though is that an element with a tabindex .= -1 attribute can be focused programmatically, So you could always set that attribute on the body of the document.不过,所有浏览器都同意的是,具有tabindex .= -1 属性的元素可以以编程方式聚焦,因此您始终可以在文档正文上设置该属性。 that shouldn't change default focus behavior of your doc.这不应该改变你的文档的默认焦点行为。

 document.body.tabIndex = 0; document.querySelector( 'input' ).onfocus = (evt) => { console.log( 'will blur in 2s' ); setTimeout( () => { console.log( 'blurring' ); document.body.focus() }, 2000 ); };
 <input placeholder="click here to gain focus">

The question is unclear at the moment.这个问题目前还不清楚。 You need to provide more code.您需要提供更多代码。

That said, you could use Angular template reference variable to blur or focus the input element.也就是说,您可以使用 Angular 模板引用变量来模糊或聚焦输入元素。 Try the following尝试以下

Template模板

<input #customInput type=text placeholder="Enter your name"/>

<button (mouseup)="blurInput(customInput)">Blur input</button>
<button (mouseup)="focusInput(customInput)">Focus input</button>

Here customInput is the template reference variable of the input element.这里customInput是输入元素的模板引用变量。

Controller Controller

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  blurInput(input) {
    input.blur();
  }

  focusInput(input) {
    input.focus();
  }
}

Working example: Stackblitz工作示例: Stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM