关于调整文本区域大小的指针

Pointers about resizing text area

本文关键字:区域 指针 文本 于调整 调整      更新时间:2023-09-26

需要一些帮助/指针....

当用户点击p元素时,我希望它的内容显示在文本区域,这样就可以修改文本等…

文本区域将具有固定的宽度。因此,当最后一个字符位于右边框时,它将自动移到较低的行。在这种情况下,为了使一个新的行,我应该计算有多少字符适合在文本区域固定宽度,每次这个数字是满足添加一个新的行?

也在情况下,用户将断行之前,它达到正确的边界,我应该搜索一个'n RegExp?(与.match ())

我认为这两种情况需要是一个timeInterval(setTimeout也许?)以毫秒为基础检查发生的所有类型。我想用纯Javascript

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <p id="p1">text text text text text text text text text text text,
            text text text text text text text text text text text,
            text text text text text text text text text text text,
            text text text text text text text text text text text.
        </p>
        <div id="holder"></div>
        <script type="text/javascript">
            var text_to_copy = document.getElementById('p1').textContent;
            //every row with a fixed text area width fits 62 characters
            var input = document.createElement("textarea");
            var holder = document.getElementById("holder");
            document.getElementById('p1').onclick = function(){
                holder.appendChild(input);
                input.id = "textarea_id";
                input.style.width = "412px";
                input.value = text_to_copy.replace(/'s{1,}/g, ' ');
                if(text_to_copy.match(''n')){
                    input.rows +=1;
                }
                /*setTimeout(function(){
                    if ((text_to_copy.length % 62) == 0){
                        input.rows += 1;
                    }
                },300);*/
            }
        </script>
    </body> 
</html>

你可以使用clientHeight vs scrollHeight来调整文本区域的高度以匹配滚动高度

这是你的代码的工作副本

var text_to_copy = document.getElementById('p1').textContent;
var input = document.createElement("textarea");
var holder = document.getElementById("holder");
document.getElementById('p1').onclick = function(){
  holder.appendChild(input);
  input.id = "textarea_id";
  input.style.width = "412px";
  input.value = text_to_copy.replace(/'s{1,}/g, ' ');
  //This function reset the textarea height base on his content. (when text is added/removed)
  var setTextAreaHeight = function(){
    input.style.height = '5px'; // Set to minimum height possible to create vertical scroll bars
    input.style.height = input.scrollHeight + 'px'; // remove the scroll bars
  }
  //call it once
  setTextAreaHeight();
  //attach to changes/key pressing.
  input.onkeydown = setTextAreaHeight;
  input.onkeyup = setTextAreaHeight;
  input.onchange = setTextAreaHeight;
};
        <p id="p1">text text text text text text text text text text text,
            text text text text text text text text text text text,
            text text text text text text text text text text text,
            text text text text text text text text text text text.
        </p>
        <div id="holder"></div>