最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Button retains focused after click - Stack Overflow

programmeradmin2浏览0评论

I have a button, that when clicked, navigates to another route. The relative code is:

<button (click)="goBack()" mat-button
      aria-label="Previous Screen" role="navigation">
      <mat-icon>keyboard_arrow_left</mat-icon>
</button>

And the click handler:

  goBack() {
    this.location.back();
  }

When I click the button, the route changes, but the button gains focus. Is that what am I doing wrong?

I have a button, that when clicked, navigates to another route. The relative code is:

<button (click)="goBack()" mat-button
      aria-label="Previous Screen" role="navigation">
      <mat-icon>keyboard_arrow_left</mat-icon>
</button>

And the click handler:

  goBack() {
    this.location.back();
  }

When I click the button, the route changes, but the button gains focus. Is that what am I doing wrong?

Share Improve this question asked Nov 6, 2018 at 12:22 RaidenFRaidenF 3,5415 gold badges27 silver badges44 bronze badges 3
  • 1 I would argue that it is good that an element with which the user interacts gains focus, and I would argue that it is good that the user is aware where the focus is. Why? Accessibility. – Theraot Commented Nov 6, 2018 at 12:29
  • This flow is natural and also user-friendly. Do you wish to change focus? – sidd Commented Nov 6, 2018 at 12:33
  • I would go with adi's solution. But its probably a bug in the angular material design library – Jesse de gans Commented Nov 6, 2018 at 12:45
Add a ment  | 

2 Answers 2

Reset to default 4

You want to be looking at the HTMLElement.blur() functionality. I'm not too familiar with Angular, but you need to have access to the event and its target in order to do so.

Something like this should work:

<button (click)="goBack($event)" mat-button
      aria-label="Previous Screen" role="navigation">
      <mat-icon>keyboard_arrow_left</mat-icon>
</button>

And for the JS:

goBack(event) {
    event.target.blur()
    this.location.back();
  }

The easiest solution would be:

button:focus {
  outline: none;
}

However, removing the outline from a button is definitely bad for accessibility. There are users who can't control a mouse, and need to be able to tab through a page with the keyboard. Removing the outline makes that very difficult. It's probably better to prevent the button from receiving focus on click.

In my opinion, calling e.preventDefault() in onMouseDown is a cleaner solution. This is certainly an accessibility friendly solution (however the solution may not be patible with your project).

Multiple clean and accesible solutions can be found here.

Cheers!

发布评论

评论列表(0)

  1. 暂无评论