0
我想顯示在另一個textarea的一個textarea中鍵入/粘貼/剪切/刪除的內容。但是當按下退格鍵和刪除鍵時我遇到了問題。我可能會遇到刪除選擇,剪切,粘貼,撤消,重做等問題。我怎樣才能最好地解決這個問題?代碼:如何同步兩個textareas?
<html>
\t <head>
\t \t <title>Live Text Sync</title>
\t \t <meta charset="utf-8"/>
\t </head>
\t <body>
\t \t <textarea id="a"></textarea>
\t \t <textarea id="b"></textarea>
\t \t <script>
\t \t \t var a = document.getElementById("a");
\t \t \t var b = document.getElementById("b");
\t \t \t a.onkeydown = function(e) {
\t \t \t \t if(!e.ctrlKey) {
\t \t \t \t \t if (e.which >= 65) {//A
\t \t \t \t \t \t var letter = String.fromCharCode(e.which);
\t \t \t \t \t \t if (!e.shiftKey) letter = letter.toLowerCase();
\t \t \t \t \t \t b.value = b.value.substring(0, a.selectionStart) + letter + b.value.substring(a.selectionEnd);
\t \t \t \t \t } else if (e.which === 8) {//backspace
\t \t \t \t \t \t \t var text = b.value;
\t \t \t \t \t \t \t var till = a.selectionStart === 0 ? 0 : a.selectionStart - 1;
\t \t \t \t \t \t \t b.value = text.substring(0, till) + text.substring(a.selectionEnd);
\t \t \t \t \t } else if (e.which === 46) {//delete
\t \t \t \t \t \t var text = b.value;
\t \t \t \t \t \t var van = text.length < a.selectionEnd ? a.selectionEnd : a.selectionEnd + 1;
\t \t \t \t \t \t b.value = text.substring(0, a.selectionStart) + text.substring(van);
\t \t \t \t \t }
\t \t \t \t }
\t \t \t \t
\t \t \t }
\t \t </script>
\t </body>
</html>