Copying text of textarea into div with line breaks

前端 未结 5 1941
春和景丽
春和景丽 2020-12-31 09:15

I am tying to make a simple effect using keyup() in jQuery. I just want that when user types into the textarea then the text which user types will

相关标签:
5条回答
  • 2020-12-31 09:21

    Add a white-space: pre-wrap rule to the div's CSS.

    .mas {
        white-space: pre-wrap;
    }
    

    Demo: http://jsfiddle.net/Pqygp/13/

    0 讨论(0)
  • 2020-12-31 09:26

    Use this line: Fiddle

    $('.'+contentAttr+'').html(value.replace(/\n/g,"<br>"));
    

    The problem was that newlines don't create linebreaks in html, but <br> will.

    0 讨论(0)
  • 2020-12-31 09:29

    You need to convert the literal newlines into <br> tags for proper output in the DIV.

    $('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>'));
    

    Shown in your code below:

        $('.content:not(.focus)').keyup(function(){					
                                        
                                        
            var value = $(this).val();
            var contentAttr = $(this).attr('name');
            
            $('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>')); //convert newlines into <br> tags
            
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea name="mas" rows="15" class="content"></textarea> <p>&nbsp;</p> <div class="mas" >Texts Comes here</div>

    JSFiddle

    0 讨论(0)
  • 2020-12-31 09:39

    Try like

    var value = $(this).();
    var contentAttr = $(this).attr('name');
    
    $('.'+contentAttr+'').html(value.replace(/\r?\n/g,"<br>"));
    

    This is the DEMO

    0 讨论(0)
  • 2020-12-31 09:39

    If you use React:

    render() {
      const nbOfTextareaRows = this.state.textareaValue.split('\n').length;
    
      return (
        <textarea
          value={this.state.textareaValue}
          onChange={e => this.setState({ textareaValue: e.target.value })}
          rows={nbOfTextareaRows}
        />
      );
    }
    
    0 讨论(0)
提交回复
热议问题