You need to enable JavaScript to run this app. 如何把选中文本从textarea输出改为按次新增到带someclass类的div中
优惠活动
大模型
产品
解决方案
定价
更多

如何把选中文本从textarea输出改为按次新增到带someclass类的div中

代码调整方案

核心改动点:

  • 修正原有选中文本的取值逻辑,统一把获取到的选中内容转成纯字符串,避免出现[object Selection]这类异常显示
  • 移除原有向textarea写入内容的逻辑,改为每次触发按钮点击时,动态创建一个独立的、带someclass类的div,将本次选中的文本写入后追加到页面,实现多次选中内容的累计存储
  • 删除原代码中用于展示的form和textarea元素

小提示:如果不想让生成的div直接堆在页面末尾,可以提前在HTML里加一个空的容器节点,把所有生成的someclass div统一放到容器内,排版会更灵活

完整可运行代码

调整后的HTML代码

<p>Select any part of this sentence 
    and press the button. Select any part of this sentence 
    and press the button. Select any part of this sentence 
    and press the button</p> 

<br>

<input type="button"
        value="Get Selection" 
        onmousedown="getSelectedText()">

<!-- 原代码中包裹textarea的form和textarea已全部移除 -->

调整后的JS代码

function getSelectedText() { 
    let selectedText = ''; 

    // 兼容不同浏览器的选中文本获取逻辑
    if (window.getSelection) { 
        selectedText = window.getSelection().toString(); 
    } else if (document.getSelection) { 
        selectedText = document.getSelection().toString(); 
    } else if (document.selection) { 
        selectedText = document.selection.createRange().text; 
    } else return; 

    // 未选中任何文本时直接返回,避免生成空div
    if (!selectedText.trim()) return;

    // 新建独立的someclass div
    const selectionItem = document.createElement('div');
    selectionItem.className = 'someclass';
    selectionItem.textContent = selectedText;

    // 将新div追加到页面,实现内容累计存储
    // 如需放到指定容器,把下面这行替换为  document.getElementById('你的容器ID').appendChild(selectionItem)
    document.body.appendChild(selectionItem);
}

内容的提问来源于stack exchange,提问作者RR Suthar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 17:06:04