0

我希望有人能帮助我。

我应该创建一个函数,将光标在我的 textarea 中的位置或选择的位置(如果可能)保存在变量中,或者如果光标不在 textarea 中,则可以为我保存 null 的值。

我最终应该实现另一个函数(使用上面保存的值)回复我前面的情况。

你知道这是否可能吗?

4

1 回答 1

0

如果您使用的是“模板”,这很容易(尽管您问题的“回复我”部分有点含糊)。

我提供了一个使用“Smarty”的简单示例,该示例使用“保存”按钮模拟“编辑”文本区域,按下时会提交文本区域以及光标位置。

当 textarea 重新加载时,它会获取值并将光标位置设置为原来的位置。它从 HTML/模板开始:

<!--
Form with textarea, save button and hidden input, simulating an "Edit" UI.
-->
<form method="post">
<textarea id="textarea" rows="12" cols="40" autofocus>
one
two
three
and

some

more...
</textarea><br>
<button onclick="setpos()">save</button>
<input type="hidden" id="pos" name="pos" value="0">
</form>
<script>
// The template code places the hidden input's value into the the following 
// variable; then, if non-zero, sets the texarea's cursor posotion to it.
var p = "{$POS}";
if (p) document.getElementById('textarea').setSelectionRange(p,p);
// Set the input's value to the cursor position.
function setpos() {
  var p = document.getElementById('textarea').selectionStart;
  document.getElementById('pos').value = p;
}
</script>

PHP 代码就是这么简单:

<?php
// Set input if not set (the first run).
!isset($_POST['pos']) and $_POST['pos'] = '0';
// Load the template engine (from the 'demo' directory).
require '../libs/Smarty.class.php';
$smarty = new Smarty;
// Assign the input for use by template:
$smarty->assign("POS",$_POST['pos']);
// Display the form:
$smarty->display('pos.tpl');

当然,如果您没有/想要 Smarty(或 PHP!),请添加更多关于您的代码的信息。

但这显示了在文本区域中获取和设置光标位置的基本原理。

于 2016-02-25T00:50:54.147 回答