如何用JavaScript修改textarea中选中文字的字体?现有函数修改全部文本
Got it, I see the problem you're facing—trying to change the font of only selected text in a textarea ends up modifying everything instead. The root issue here is that textarea elements only support plain text, so you can't apply different styles to parts of the text inside them.
To fix this, you'll want to use a contenteditable div instead (it acts like a textarea but allows rich text formatting). Here's how you can modify your code to target only the selected text for font changes:
Step 1: Replace Textarea with Contenteditable Div
Swap out your textarea for a div that’s set to be editable:
<div id="editor" contenteditable="true" style="width: 400px; height: 200px; border: 1px solid #ccc; padding: 8px; font-size: 16px;"></div> <button onclick="changeFont('Arial')">Arial</button> <button onclick="changeFont('Georgia')">Georgia</button> <button onclick="changeFont('Courier New')">Courier New</button>
Step 2: Add the Font Change Function
This JavaScript will target only the selected text and apply the desired font:
function changeFont(fontFamily) { // Get the user's selected text range const selection = window.getSelection(); if (!selection.rangeCount) return; // Exit if nothing is selected const range = selection.getRangeAt(0); // Create a span to wrap the selected text with the new font const styleSpan = document.createElement('span'); styleSpan.style.fontFamily = fontFamily; // Wrap the selected content in the styled span range.surroundContents(styleSpan); // Restore the selection so the user doesn't lose their focus selection.removeAllRanges(); selection.addRange(range); }
How This Works
window.getSelection()grabs the exact text the user has highlighted.- We create a
<span>element with the chosen font family and wrap the selected text in it—this applies the style only to that portion. - Restoring the selection keeps the user’s cursor positioned correctly after the change.
If you absolutely need to use a textarea (for plain text workflows), rich text formatting isn’t possible natively. You’d have to use a markup system (like adding [font=Arial]selected text[/font]) and render the formatted text elsewhere. But for in-place rich text editing, the contenteditable div is the straightforward solution.
内容的提问来源于stack exchange,提问作者user8991131

