簡體   English   中英

Safari:焦點事件對按鈕元素不起作用

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

焦點事件在所有瀏覽器上都可以正常工作,但在 Safari 上單擊它時。

它適用於 div[tabindex] 元素,但不適用於 button 或 input:button 元素。

當我使用 $('.btn').focus() 時,它也可以獲得焦點事件。

為什么單擊時未觸發焦點事件?

這是我的代碼:

 $(".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>

為什么單擊時未觸發焦點事件?

我們通過研究發現 Mac 上的 Safari 和 FireFox 在您單擊按鈕時不會將焦點設置在按鈕上。

我們解決這個問題的方法是向我們的按鈕添加一個點擊監聽器,並在被點擊的按鈕上調用 focus()。

在 Angular 中,它看起來像這樣:

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

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

這在 MacOS 上按預期工作。 單擊按鈕、單選按鈕或復選框不會使元素獲得焦點 - 因此它不會失去焦點並觸發模糊。

解決方案是給它一個單擊事件,使元素獲得焦點。

這可能會解決問題: https : //stackoverflow.com/a/1269767/2731261

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

Angular 8+ 解決方案:

  1. 在您的按鈕標簽中添加 #toggleButton 和 (click)="onClick(); $event.stopPropagation()"

經驗:

<button #toggleButton type="button"
    (click)="onClick(); $event.stopPropagation()"></button>
  1. 在你的 component.ts 添加 ==>before 構造函數

*** @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