You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将select()选中文本存入变量并实现加粗?textarea替代方案咨询

解决方案:用contentEditable div实现选中文本加粗功能

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:11:08