如何将select()选中文本存入变量并实现加粗?textarea替代方案咨询
Hey there! Let's break down how to solve this problem you're facing.
First off, you’re totally right—<textarea> elements don’t support rich text formatting like bolding selected content out of the box. That’s why switching to a contenteditable <div> is the ideal workaround here. It lets you work with rich text directly, and we can easily handle selecting text, storing it in a variable, and applying that bold formatting you need.
Here’s a full, working implementation tailored to your needs:
1. Replace your textarea with a contenteditable div
Swap out your existing <textarea id="article"> with this editable div (you can style it to match your original textarea’s look):
<div id="article" contenteditable="true" style="border: 1px solid #ddd; padding: 10px; min-height: 200px; font-family: Arial, sans-serif;"> Type or paste your content here, then select text and click the button to bold it! </div> <button onclick="formatSelectedText()">Bold Selected Text</button>
2. JavaScript to handle selection, variable storage, and bolding
Add this JavaScript function to capture the selected text, store it in a variable, and apply bold formatting:
function formatSelectedText() { // Get the user's selection const selection = window.getSelection(); if (!selection.rangeCount) return; // Exit early if nothing is selected // Store the selected text in a variable (use this however you need) const selectedContent = selection.toString(); console.log('Selected text:', selectedContent); // Example of using the variable // Create a <strong> element to wrap the selected content (renders as bold) const boldTag = document.createElement('strong'); // Grab the selected range and wrap it with the bold element const selectedRange = selection.getRangeAt(0); selectedRange.surroundContents(boldTag); // Optional: Clear the selection after formatting selection.removeAllRanges(); }
A quick breakdown of how this works:
window.getSelection()captures the text the user has highlighted in the editable div.- We save the selected text to
selectedContent—you can use this variable for logging, validation, or any other logic you need. selectedRange.surroundContents(boldTag)wraps the highlighted text in a<strong>tag, which applies bold formatting natively in the browser.
Bonus: Toggling bold (optional)
If you want to let users toggle bold on/off (so selecting already bolded text removes the formatting), you can simplify things with this alternative function:
function formatSelectedText() { const selection = window.getSelection(); if (!selection.rangeCount) return; const selectedContent = selection.toString(); console.log('Selected text:', selectedContent); // Toggle bold state using the native execCommand method const isBold = document.queryCommandState('bold'); document.execCommand('bold', false, null); }
This uses the widely supported document.execCommand() method to handle the toggle logic automatically.
内容的提问来源于stack exchange,提问作者MydroX

