2015-05-14 71 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>