textarea占位符换行在Firefox中无效,求可行解决方案
The Problem
You’ve run into a frustrating cross-browser quirk: when you set a multi-line placeholder for your textarea using \n in jQuery, it displays correctly with line breaks in Chrome, but Firefox completely ignores the newlines—collapsing your text into a single line like "Referring URL;;Link URL;;Anchor TextorURL".
Why This Happens
This all comes down to browser engine differences in how the placeholder attribute is parsed:
- Chrome (and other WebKit/Blink-based browsers) recognize
\nas a valid line break within placeholder text and render it as intended. - Firefox (Gecko engine) treats newline characters in the
placeholderattribute as collapsible whitespace by default, stripping them out entirely instead of rendering line breaks.
Fixes for Firefox
1. CSS Pseudo-element (Simplest Solution)
You can force Firefox to respect line breaks by styling the placeholder with the ::placeholder pseudo-element and adjusting the white-space property. Add this to your stylesheet:
textarea#backlinks::placeholder { white-space: pre-line; }
pre-linepreserves line breaks while collapsing extra spaces (ideal for your use case, where you only need the intentional newlines).- If you need to preserve every space and line break exactly as written, use
white-space: preinstead.
Keep your existing jQuery code as-is to set the placeholder text with \n:
$('[name=backlinks]').attr('placeholder', 'Referring URL;;Link URL;;Anchor Text\nor\nURL');
2. JavaScript-Simulated Placeholder (Fallback for Edge Cases)
If the CSS method doesn’t work for your specific setup (e.g., supporting very old Firefox versions), you can simulate the placeholder behavior manually. This bypasses the browser’s native placeholder handling entirely:
const textarea = $('#backlinks'); const placeholderText = 'Referring URL;;Link URL;;Anchor Text\nor\nURL'; // Initialize placeholder if textarea is empty if (!textarea.val()) { textarea.val(placeholderText); textarea.css('color', '#999'); // Match native placeholder gray } // Focus event: clear placeholder if it's active textarea.on('focus', function() { if ($(this).val() === placeholderText) { $(this).val('').css('color', '#000'); } }); // Blur event: restore placeholder if textarea is empty textarea.on('blur', function() { if (!$(this).val()) { $(this).val(placeholderText).css('color', '#999'); } });
This approach works across all browsers since it uses the textarea’s actual value to display the multi-line hint.
Final Notes
The CSS method is the cleanest and most maintainable option for modern browsers. Test it first, and use the JavaScript fallback only if you need to support legacy Firefox versions that don’t fully support the ::placeholder pseudo-element.
内容的提问来源于stack exchange,提问作者Nadim2014

