2016-07-28 26 views
0

我的問題是,HTML - 打破線,而獲得輸入從文本區

當我型多線在文本區域我得到如下所示的結果,

upper one is input and lower one is output

但我想要得到的輸出喜歡這個,

Image 2

在這張照片我使用<br/>只是爲了使外觀什T I想,但,在實際我不希望使用<br/>,以切斷線在多行

這是個中間代碼我使用...

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
<body> 
    <TextArea id = "Input" onKeyupUp = "showResult()" style = "height: 100px; width: 100%; resize: none;"> </TextArea> 
    <Div id = "output" ></Div> 
</body> 

<script> 
    function showResult(){ 
    var input = document.getElementById("Input").value; 
     document.getElementById("Output").innerHTML = input; 
    } 
</script> 
</html> 

回答

2

textarea使用文本格式的換行符,如\n\r\r\n。所以,簡單的正則表達式將其中的任何一個轉換爲HTML換行符:<br />將解決您的問題。

var inputHTML = input.replace(/\r\n|\r|\n/g, "<br />"); 

function showResult() { 
 
    var input = document.getElementById("Input").value; 
 
    var inputHTML = input.replace(/\r\n|\r|\n/g, "<br />"); 
 
    document.getElementById("output").innerHTML = inputHTML; 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
</head> 
 

 
<body> 
 
    <TextArea id="Input" onKeyupUp="showResult()" style="height: 100px; width: 100%; resize: none;"></TextArea> 
 
    <Div id="output"></Div> 
 
    <button onclick="showResult()">SHOW</button> 
 
</body> 
 

 
</html>

+1

謝謝你這麼多老兄...你搖滾! :d –

-1

嘗試PHP函數nl2br( )for your output

+0

在OP沒有'php'標籤。服務器甚至可能不在php中。只有客戶端js和標籤一樣有更簡單的解決方案。 – Iceman