3

通过记录 onselect 并每次存储开始和结束,我能够从文本区域中获取突出显示的文本。然后,当我单击一个按钮时,我自己构建子字符串。难道没有更简单的方法来简单地查询选择吗?

我有点期待 html5 dom 中会有所有这些事情的方法,比如:

textarea.getSelectedStart() textarea.getSelectedEnd(); textArea.setSelected(开始,结束);

另外,有没有办法以编程方式取消选择文本区域中的文本?

我正在根据下面的第一个解决方案输入代码。这种工作,但有一个奇怪的问题:

<script language=javascript>
function replaceCLOZE(code, questionType) {
  var v = code.value;
  var s = code.selectionStart;
  var e = code.selectionEnd;
  var t = v.substr(s, e-s);
  var rep = "{:" + questionType + ":="+t+"}";
  code.value = v.substr(0,s) + rep + v.substr(e,v.length-e+1);
}

function shortAnswer(code) {
  replaceCLOZE(code, "SA");
}
function shortAnswerCaseSensitive(code) {
  replaceCLOZE(code, "SAC");
}
function multipleChoice(code) {
  replaceCLOZE(code, "MC");
}

文本区域实际上具有 code.selectionStart 和 code.selectionEnd 属性。但是上面的代码现在可以工作了,它将屏幕上突出显示的文本设置为文本区域中的第一个单词。请注意, selectionStart 仍然正确,但 Firefox 中实际突出显示的内容是错误的。

在 Chrome 中它工作正常。也许这只是 Firefox 中的一个错误,或者是否应该采取其他措施来正确更新文本区域?

4

1 回答 1

5

Following is simple way to get selected text of textarea of html. Still not clear what you want as following method simply will give you selected text in alert.

<html><head>
<script>
function alertme(){
var textarea = document.getElementById("textArea");  
var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
alert (selection);
}

</script>

</head>
<body> 
<p><textarea class="noscrollbars" id="textArea"></textarea></p>
<button onclick="alertme()">Click me</button>
</body></html>

When you select text, the button will alert you what you have selected. selectionStart gives you starting point and selectionEnd gives you end point, while substring needs three arguments string, starting point and ending point.

于 2014-04-12T07:33:44.257 回答