您可以尝试使用带有contenteditable="true" 属性的<pre> 元素而不是textarea。理论上这应该保留输入。
编辑我
您可以拦截onpaste 事件并将\r\n 的所有实例标准化为\n,然后生成校验和。 JavaScript 可能如下所示:
var input_el = document.querySelector('.your-textarea');
input_el.onpaste = function(e){
typeof e !== 'undefined' && e.preventDefault();
var clipbd_data;
// handle IE edge case
if (window.clipboardData && window.clipboardData.getData) {
clipbd_data = window.clipboardData.getData('Text').replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
}
else if (e.clipboardData && e.clipboardData.getData) {
clipbd_data = e.clipboardData.getData('text/plain').replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
}
else {
return; // functionality not supported
}
input_el.value = clipbd_data;
return false;
};
注意:我没有测试过这个。
Source for regex
编辑二
拦截复制事件
首先,将以下onclick 处理程序添加到文本区域:
<textarea class="your-textarea" onfocus="this.select()" onclick="this.focus();this.select()">
</textarea>
<!-- could optionally add ontouchstart="this.select()" for phones, if you need to -->
这很重要,因为我们正在拦截copy 事件——我们不能抓取用户复制的确切数据,因为他们还没有复制它,所以我们需要强制用户选择textarea 中的所有文本都会自动传递,因此我们可以将 textarea 的全部内容传递到剪贴板(标准化后)。无论如何,这应该是用户想要做的,所以它不应该出现可用性问题......
现在,截取副本并添加您自己的文本:
var txt_area = document.querySelector('.your-textarea');
txt_area.addEventListener('copy', function(e){
// stop the normal copy behaviour
typeof e !== 'undefined' && e.preventDefault();
// get the contents of the textarea
var txt_before = txt_area.value;
// normalise
var txt_after = txt_before.replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
e.clipboardData.setData('text/plain', txt_after);
});