我有以下代码,我正在复制以下数据:
ABC123
DEF123
HIJ123
并将其粘贴到文本区域。所以粘贴代码后光标就在
HIJ123
之后,如下所示:
现在假设我在 ABC123 之后引入一条新行,如下所示:
我的光标位于 ABC123 之后的行上,然后我尝试再次在该行上粘贴这 3 条记录,结果变得一团糟,如下所示:
为什么它没有粘贴到应该粘贴的地方并且变得混乱?
let element = document.getElementById("post-text");
element.addEventListener('paste', (e) => {
e.preventDefault();
console.log(event.clipboardData);
element.value += (event.clipboardData || window.clipboardData).getData("text").trim()
});
document.getElementById('post-button').addEventListener('click', function() {
var lines = $('#post-text').val().split('\n'); //gives all lines
///var lines = element.split('\n');//gives all lines
//To paste
/*
ABC123
DEF123
HIJ123
*/
console.log(lines);
console.log(lines.length);
var firstLine = lines[0];
console.log(firstLine);
var secondLine = lines[1];
console.log(secondLine);
for (i = 0; i < lines.length; i++) {
$("#phrase").append("<div>" + lines[i] + "</div>")
}
});
#case-stack p {
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */
}
textarea {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required></textarea><br>
<input type="button" id="post-button" value="Post!">
<div id="phrase"></div>
在粘贴时添加事件监听器
$('textarea').on('paste', function(event) {
event.preventDefault();//prevent pasted text being added
// add ID so we can clear textarea
let text_area_id = $(this).attr('id');
$('#' + text_area_id).val('');
let clip = event.originalEvent.clipboardData.getData('Text');
let final_clip = clip.replace('', '\n');
console.log(final_clip);
$('#' + text_area_id).val(final_clip);
});