如何让button内的contenteditable元素在Firefox中正常工作?
The Problem
I’m trying to get a contenteditable element inside a <button> to work in Firefox the same way it does in Chrome, and it seems the button’s default behavior is blocking the editable functionality. The pure HTML snippet below works perfectly in Chrome and Edge, but fails in several Firefox versions and IE11:
- Firefox Developer Edition 61.0b7 (64-bit)
- Firefox Developer Edition 61.0b9 (64-bit)
- Firefox Nightly 62.0a1 (2018-05-14) (64-bit)
- Firefox Nightly 62.0a1 (2018-05-29) (64-bit)
- Internet Explorer 11.48.17134.0
Test Code
<button> <div contenteditable="true"> This text can be edited by the user. </div> </button>
For context: Buttons can contain any type of child element—images, editable/non-editable divs, p tags, headings, etc.—and I need this to work consistently across browsers.
Why This Happens
Native <button> elements are interactive form controls, and browsers like Firefox and IE11 prioritize the button’s default behaviors (handling clicks, focus states, form submission) over letting internal elements act as editable regions. The browser intercepts interactions that would normally trigger the contenteditable functionality.
Solutions
1. Replace <button> with a Semantic Div (Recommended)
Instead of using a native button, simulate its behavior with a <div> while maintaining accessibility. This avoids the browser’s default blocking behavior entirely:
<div role="button" tabindex="0" style="padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px; background-color: #f8f9fa; cursor: pointer; display: inline-block;" > <div contenteditable="true"> This text can be edited by the user. </div> </div>
role="button"tells screen readers this element acts like a button for accessibility.tabindex="0"lets the div receive focus via keyboard navigation.- The basic styling mimics a default button (adjust as needed for your design).
2. Use JavaScript to Override Button Behavior
If you must keep the native <button>, you can intercept clicks and force focus on the editable element. Note this may have edge cases (e.g., clicking outside the editable area within the button):
<button onclick="event.preventDefault(); document.querySelector('[contenteditable]').focus();"> <div contenteditable="true"> This text can be edited by the user. </div> </button>
Related Bug Context
This is a known issue in older Firefox versions—there are active bug reports tracking the conflict between native button controls and internal contenteditable elements. While newer Firefox releases may have addressed this, the workarounds above are reliable for broader browser support.
内容的提问来源于stack exchange,提问作者guitartsword

