简体   繁体   English

文本区域内的换行符 html

[英]Line break inside text area html

I'm making a form to fill in and create a pdf through, but I'm facing a problem with text area, I want the user to input text and while writting and pressing space to go back to line like this:我正在制作一个表格来填写并创建一个 pdf ,但是我遇到了文本区域的问题,我希望用户输入文本并在向 go 写入和按下空格时像这样返回: 在此处输入图像描述

i want it to automatically show in the pdf but instead i get this:我希望它自动显示在 pdf 中,但我得到了这个: 在此处输入图像描述

how can i fix it?我该如何解决? the code for this is:代码是:

<div class="mb-2"><textarea name="element" placeholder="Elements à fournir" class="form-control"></textarea></div>

You need to convert the line breaks from the textarea ( \r or \n ) into line breaks your PDF can understand ( <br /> <div> <li> etc).您需要将文本区域中的换行符( \r\n )转换为 PDF 可以理解的换行符( <br /> <div> <li>等)。

a simple PHP way is一个简单的 PHP 方式是

$string = nl2br($string);
// converts \n to <br />

If you need to transform those line breaks on the fly (like you're capturing the input and displaying it formatted as the user types), then do it in javascript.如果您需要即时转换这些换行符(例如您正在捕获输入并将其显示为用户类型的格式),请在 javascript 中进行。 Here is a handy function taken from: https://stackoverflow.com/a/7467863/1772933这是一个方便的 function 取自: https://stackoverflow.com/a/7467863/1772933

function nl2br (str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

Here is an example of how to use that function as the user is typing这是用户键入时如何使用 function 的示例

$('#TextArea').keypress(function(evt){
        $('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
        $('#pdfPreviewArea').html($('#TextArea').val()); // copy to #pdfPreviewArea
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM