简体   繁体   English

Safari:焦点事件对按钮元素不起作用

[英]Safari: focus event doesn't work on button element

The focus event works fine on all browsers but Safari when it has been clicked.焦点事件在所有浏览器上都可以正常工作,但在 Safari 上单击它时。

And it works fine on div[tabindex] element, but don't work on button or input:button element.它适用于 div[tabindex] 元素,但不适用于 button 或 input:button 元素。

It also can get the focus event when I use $('.btn').focus().当我使用 $('.btn').focus() 时,它也可以获得焦点事件。

Why does the focus event haven't triggered on click ?为什么单击时未触发焦点事件?

Here is my code:这是我的代码:

 $(".btn").focus(function (e) { $(".result").append("<p>Event:"+e.type+", target:"+e.target+"</p>"); })
 .result{min-height:200px;border:1px solid #000;}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="btn">button 1</button> <input type="button" class="btn" value="button 2"/> <div class="btn" tabindex="0">div element</div> <h1> Result: </h1> <div class="result"> </div>

Why does the focus event haven't triggered on click ?为什么单击时未触发焦点事件?

We found through research that Safari and FireFox on Macs do not set focus on buttons when you click on them.我们通过研究发现 Mac 上的 Safari 和 FireFox 在您单击按钮时不会将焦点设置在按钮上。

The way we fixed that was to add a click listener to our buttons and call focus() on the button that was clicked.我们解决这个问题的方法是向我们的按钮添加一个点击监听器,并在被点击的按钮上调用 focus()。

In Angular it looked like this:在 Angular 中,它看起来像这样:

<button (click)="myClickFunction(); $event.target.focus();>My Button</button>

See https://bugs.webkit.org/show_bug.cgi?id=13724https://bugs.webkit.org/show_bug.cgi?id=13724

This is working as intended on MacOS.这在 MacOS 上按预期工作。 Clicking a button, radio button, or checkbox doesn't give the element focus- thus it can't lose focus and trigger a blur.单击按钮、单选按钮或复选框不会使元素获得焦点 - 因此它不会失去焦点并触发模糊。

The solution is to give it a click event that gives the element focus.解决方案是给它一个单击事件,使元素获得焦点。

This might fix the issue: https://stackoverflow.com/a/1269767/2731261这可能会解决问题: https : //stackoverflow.com/a/1269767/2731261

$(".btn").mouseup(function(e){
    e.preventDefault();
});

Angular 8+ solution: Angular 8+ 解决方案:

  1. in your button tag add #toggleButton and (click)="onClick(); $event.stopPropagation()"在您的按钮标签中添加 #toggleButton 和 (click)="onClick(); $event.stopPropagation()"

exp:经验:

<button #toggleButton type="button"
    (click)="onClick(); $event.stopPropagation()"></button>
  1. in your component.ts add ==>before constructor在你的 component.ts 添加 ==>before 构造函数

*** @ViewChild('toggleButton', { static: true }) toggleButton: ElementRef; *** @ViewChild('toggleButton', { static: true }) toggleButton: ElementRef;


onclick(){
        this.toggleButton.nativeElement.focus();
}

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

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