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

时间:2015-05-14 10:47:39

标签: javascript regex textarea

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

当用户点击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>

1 个答案:

答案 0 :(得分:1)

您可以使用clientHeight vs scrollHeight

调整textarea高度以匹配滚动高度

以下是代码的工作副本

&#13;
&#13;
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;
};
&#13;
        <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>
&#13;
&#13;
&#13;