如何替换textarea中的文本?

我需要在所选文本下方的文本区域内显示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(); }); }); 

这是我的傻瓜

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

提前致谢。

您可以对div使用position: fixed ,并在开始选择时计算它。 选择文本后,使用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} 
    

***