在文本区域中显示换行符的分隔符

4
我希望HTML5的<textarea>标签在存在“硬”换行时能够有视觉表示,以区别于自动换行。例如,给定以下文本:
    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.
我希望有一些视觉指示,表明由换行符分隔的行,如空格:
    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.
在换行符的位置插入可视字符或文本字符串(如¶)也可以起到相同作用,即:
    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.
理想情况下,我希望能够使用CSS来实现此功能,但我不确定是否存在适当的机制。
如果可能的话,我希望不必修改textarea的内容。
我还希望使用“纯”的textarea标签(而不是例如TinyMCE)。
谢谢您阅读,期待您的想法和建议。

1
你可能会设置一些限制,使得问题难以回答,但这个问题很好。 - Álvaro González
2个回答

6

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>

注意:仅在Firefox 3.6.x上进行过测试。(IE需要不同的CSS来设置透明度)


2
"T1"是一个文本区域的ID。使用jQuery:
var content = $('#T1').html().replace(/¶/g,"") //get rid of existing indicator
content = $('#T1').html().replace(/\n/g,"¶\n") //add indicator
$('#T1').html(content)

你无法在不修改文本区域内容的情况下完成此操作。你无法在页面上看到没有的内容。在保存前需要删除段落字符。将代码与onkeyup事件相连接。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接