在<text区域>使用JavaScript

Shuffle selected text on <textarea> using JavaScript

本文关键字:使用 JavaScript gt text lt 区域      更新时间:2023-09-26

当我用鼠标在<textarea>上选择一些文本时,如何通过单击按钮来对其进行混洗/加扰?

我在SO上搜索了一些类似于我想要的东西,我看到一些人使用substringselectionStartselectionEnd

我想要的是:当我用鼠标选择一些文本时,当我点击一个按钮时,它会被打乱/打乱,而<textarea>上未被选择的其余文本应该保持原样。

我只想对选定的文本执行操作。

它更类似于富文本编辑器,比如当您选择一些文本,然后单击bold按钮时,所选文本将变为bold=

p.S。它应该按单个字符进行混洗

编辑:明白了!我只需要分离选择字符串。我的代码现在可以工作了。这很有帮助-https://stackoverflow.com/a/9605191/1101391

不幸的是,IE 9及以下版本不支持<input><textarea>上的selectionStartselectionEnd属性。以下是对我有效的解决方案-https://stackoverflow.com/a/9276457/1101391

您可以访问全文,并知道选择开始和结束的子字符串。试试这样的东西:

var txtArea = document.getElementById("foo");
var before = txtArea.value.substr(0, txtArea.selectionStart);
var selection = txtArea.value.substr(txtArea.selectionStart, txtArea.selectionEnd + 1);
var after = txtArea.value.substr(txtArea.selectionEnd, txtArea.value.length);
txtArea.value = before + scrambleThisString(selection) + after;

假设您使用ID content:命名文本区域

var textarea = document.getElementById('content');
var content = textarea.value;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = content.slice(0, start);
var after = content.slice(end);
var selected = content.substring(start, end);
selected = shuffleStringByMagic(selected);
textarea.value = before + selected + after;