博客 / 詳情

返回

狀態為禁用 disabled 的 input 元素,監聽點擊事件的問題

問題現象:

狀態為 disabled 的 input 不在自身和父級觸發點擊事件

問題原因:

Google Chrome 瀏覽器在更新 116 版本之後,禁止了狀態為 disabled 的 input 的事件冒泡。

可能的解決方法:

  1. 對於 input 元素,使用 readonly 替代 disabled;
  2. 如果在 input 的父級做監聽,可以對 input 使用 pointer-events: none; 的樣式;
  3. 如果監聽綁定在 input 本身,用 pointerup/pointerdown 替代 click 事件;

問題詳情:

https://bugs.chromium.org/p/chromium/issues/detail?id=1477379...

https://support.google.com/chrome/thread/231871942/click-even...

Google Chrome 瀏覽器在更新 116 版本之後,禁止了狀態為 disabled 的 input 的事件冒泡。
這項改動的解釋是“為了對齊HTML標準和Firefox的行為( in order to conform to the HTML spec and firefox's behavior)”。

即造成如下後果:

<div id="wrapper">
    <input id="ipt" disabled>
</div>
<script>

document.querySelector('#wrapper').addEventListener('click', () => { console.log('div 內被點擊') })

document.querySelector('#ipt').addEventListener('click', () => { console.log('input 被點擊') })
</script>

以上代碼的兩個事件都不會被觸發;

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.