2015-05-14 72 views
0

需要一些帮助/指针....指针关于变更文本区域

当用户会点击AP元素我希望它的内容显示在一个文本区域,因此将有可能修改的文字和etc ...

文本区域的宽度是固定的。因此,当最后一个字符位于右边界时,它将自动位于下一行。在这种情况下,为了创建一个新行,我是否应该计算在文本区域固定宽度中有多少个字符适合并且每次满足这个数字以添加新行?

在用户将打破行到达右边界之前,我应该寻找一个\ n正则表达式?(有.match()?)

我认为,这2情况下需要的情况下

还是一个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> 
+0

只是一个说明。我认为\ n表示断线(例如,当用户按下输入时)。它是否也包含简单的空白空间? 我在问,因为警报(text_to_copy.search('\ n'));返回55 – Anamed

+0

请编辑您的问题,而不是评论。 –

回答

1

您可以调整textarea的高度使用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>