如何替换textarea中的文本? [英] How to replace the text in textarea?

查看:425
本文介绍了如何替换textarea中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to display a div inside text area below selected text.

Javascript:

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,直到选中文字。

my requirement is to replace the text with stars,on selection of text in textarea the div with "***" must be shown below the selected text and after clicking on stars the text must be replaced with stars and div must be hidden utill the text is selected.

谢谢提前。

推荐答案

您可以使用位置:固定为您的div并在开始选择时计算它。选择文本后,使用jQuery offset 方法设置其位置:

You can use position: fixed for your div and calculate it when you start the selection. And when the text is selected, use jQuery offset method to set its position:

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>

这篇关于如何替换textarea中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆