Show separation between newlines in textarea

2019-02-18 19:45发布

问题:

I would like to have the visual representation of an HTML5 <textarea> tag indicate when there are 'hard' newlines as opposed to wrapping. For example, given the text:

    Hello, world\n
    How are you, and this text
    wraps to a new line because
    it's too long.\n
    But this is a proper new line.

I would like to have some visual indication of the lines separated by newlines such as white-space:

    Hello world

    How are you, and this text
    wraps to a new line because
    it's too long.

    But this is a proper new line.

Inserting a visual character or text string in place of the newline such as ¶, could also work i.e.

    Hello world¶
    How are you, and this text
    wraps to a new line because
    it's too long.¶
    But this is a proper new line.

Ideally I'd like to be able to do this with CSS, but I'm not sure what the appropriate (if it even exists) mechanism would be for such a visual representation.

I'd prefer to not have to modify the contents of the textarea, if possible.

I'd also prefer to work with a "pure" textarea tag (as opposed to e.g. TinyMCE).

Thank you for reading, any thoughts and suggestions would be appreciated.

回答1:

Live Demo

<style type="text/css">
#myform textarea {
    border: 1px solid #000;
    position: absolute;
}
#myform #source {
    background: transparent;
    z-index: 1;
}
#myform #mirror {
    color: rgba(0,0,0,0.5);
    z-index: -1;
}
</style>

<script type="text/javascript">
$("#source").keyup(function() {
    $("#mirror").val($("#source").val().replace(/\n/g,"¶\n"));
});
</script>

<form id="myform">
    <textarea id="source" rows="10" cols="40"></textarea>
    <textarea id="mirror" rows="10" cols="40"></textarea>
</form>

Note: Tested on Firefox 3.6.x only. (IE will need some different CSS for opacity)



回答2:

"T1" is the ID of a textarea. Using jQuery:

var content = $('#T1').html().replace(/¶/g,"") //get rid of existing indicator
content = $('#T1').html().replace(/\n/g,"¶\n") //add indicator
$('#T1').html(content)

You cannot do this without modifying the content of the textarea. You can't see what you don't have in your page. You'd need to strip out the paragraph character before saving. Hook up the code to the onkeyup event.