【问题标题】:How to replace the text in textarea?如何替换textarea中的文本?
【发布时间】:2018-01-25 06:55:47
【问题描述】:

我需要在所选文本下方的文本区域内显示一个 div。

Javascript:

function getSel() {
    var txtarea = document.getElementById("mytextarea");
    var start = txtarea.selectionStart;
    var finish = txtarea.selectionEnd;
    var allText = txtarea.value;
    var sel = "****";
    var newText = 
        allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
}
$(document).ready(function () {
    $('#newpost').hide();
    $('#mytextarea').on('select', function () {
        $('#newpost').show();
    });
});

这是我的plunker

我的要求是用星号替换文本,在 textarea 中选择文本时,带有“***”的 div 必须显示在所选文本下方,点击星号后,文本必须用星号替换,div 必须是隐藏直到文本被选中。

提前致谢。

【问题讨论】:

  • 无法理解您的要求。能不能解释的更清楚一点?
  • @trgiangvp3 当我在文本区域中选择一些文本时,我需要在该文本下方显示星号,因此在选择星号时,所选文本必须更改为星号。
  • 如果文本区域内的文本太长,必须多行显示怎么办?选择文本时,您希望如何显示星星字符?
  • @trgiangvp3 实际上只选择了部分文本,而不是整个文本,所选文本必须用星号替换。星号必须计算所选文本。

标签: javascript jquery


【解决方案1】:

您可以将position: fixed 用于您的 div 并在您开始选择时计算它。并且当文本被选中时,使用 jQuery offset 方法来设置它的位置:

function getSel() {
    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;

    // obtain the selected text
    var sel = Array(finish - start + 1).join("*");
    //append te text;
    var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
    
    $('#newpost').offset({top: 0, left: 0}).hide();
}

$(document).ready(function () {
    var position;
    $('#newpost').hide();
    $('#mytextarea').on('select', function (e) {
        $('#newpost').offset(position).show();
        var txtarea = document.getElementById("mytextarea");
        var start = txtarea.selectionStart;
        var finish = txtarea.selectionEnd;
        $('#newpost p').text(Array(finish - start + 1).join("*"));
    }).on('mousedown', function(e) {
        position = {top: e.pageY - 5, left: e.pageX};
    });
});
#mytextarea {width: 300px; height: 100px; overflow:hidden}
#newpost{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <textArea id="mytextarea"></textArea>
  <div id="newpost">
    <p onclick="getSel()">***</p>
  </div>
</body>

【讨论】:

  • 谢谢。但这里的星数必须与所选文本数相同。
  • 星号必须在所选文本下方,它们在其他位置,如何更改 x 和 y 位置。以便它们可以精确定位在所选文本下方
  • 您可以在此处从e.pageY 中减去几个像素:position = {top: e.pageY - 10, left: e.pageX};。检查更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多