javascript - 如何将此选定的文本放入DIV而不是textarea,并将所有选定的部分一一收集到div中
问题描述
这是一个简单的脚本,可以在文本区域中获取选定的文本。
但我想在这里做一些改变。
我想将这些选定的文本放入 div someclass 而不是 textarea,每次当我选择文本并单击Get Selection
按钮时,然后将选定的文本添加到新的 div someclass 中。
像这样:
<div class='someclass'> the first time selection</div>
<div class='someclass'> second selection </div>
<div class='someclass'> third selection </div>
<div class='someclass'> fourth selection </div>
... and so on
Plz我不知道我该怎么做,请让它解决。
我的整个代码在这里:
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// To write the selected text into the textarea
document.testform.selectedtext.value = selectedText;
}
<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()">
<!--Form to show the selected text as output-->
<form name="testform">
<textarea name="selectedtext"
rows="5"
cols="20"></textarea>
在此先感谢,爱你请解决它。
解决方案
据我了解,您需要将选择文本附加到新元素
我们开始吧,看看片段
// Function to get the Selected Text
function getSelectedText() {
var selectedText = '';
// #### create a new element with variable (nw) #### //
var nw = document.createElement("div"); // Element's tag
nw.className = "NEWCLASS"; // Element's class name
nw.style.textAlign = "center"; // some applied style
// window.getSelection
if (window.getSelection) {
selectedText = window.getSelection();
}
// document.getSelection
else if (document.getSelection) {
selectedText = document.getSelection();
}
// document.selection
else if (document.selection) {
selectedText =
document.selection.createRange().text;
} else return;
// #### get the Selected text appended to body #### //
nw.innerHTML = selectedText;
document.body.appendChild(nw); // Append element to body
}
<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()">
推荐阅读
- react-native - Expo 或 React Native CLI
- javascript - KnockoutJS Observable 未在模板中更新
- objective-c - UICollectionView 动态高度和宽度
- javascript - {`${props.title} `} 和 {props.title} 之间的区别
- google-sheets-formula - 如何在 GoogleSheets 中使用 TODAY() 函数和 GOOGLEFINANCE() 函数
- c - 在 Ubuntu 的 C 代码中无法生成哔哔声
- sqlite - KnexJs - 删除级联时的 Sqlite3 不起作用
- python - ValueError:发现样本数量不一致的输入变量:[249957、8248581]
- git - Git索引和提交很慢
- reactjs - 无法让功能组件中的异步代码表现得像类组件