绑定到
keyup事件时,您会注意到延迟。通常绑定到
keydown事件时,文本区域的值尚未更改,因此,在确定
keydown事件期间按下的键之前,您无法更新第二个文本区域的值。对我们来说幸运的是,我们可以使用
String.fromCharCode()将新按下的键附加到第二个文本区域。这样做是为了使第二文本区域快速更新而没有任何滞后:
$('.one').on('keydown', function(event){ var key = String.fromCharCode(event.which); if (!event.shiftKey) { key = key.toLowerCase(); } $('.two').val( $(this).val() + key );});这是一个演示:http :
//jsfiddle.net/agz9Y/2/
这将使第二个文本区域具有与第一个文本区域相同的内容,如果您想将第一个文本区域附加到第二个文本区域,则只需将第一个文本区域的值添加到第二个文本区域即可,而不是覆盖:
$('.one').on('keydown', function(event){ var key = String.fromCharCode(event.which); if (!event.shiftKey) { key = key.toLowerCase(); } $('.two').val( $('.two').val() + $(this).val() + key );});这是一个演示:http :
//jsfiddle.net/agz9Y/3/
更新资料
您可以对此进行一些更改,以便
.two元素记住其自己的值:
$('.one').on('keydown', function(event){ var key = String.fromCharCode(event.which); if (!event.shiftKey) { key = key.toLowerCase(); } //notice the value for the second textarea starts with it's data attribute $('.two').val( $('.two').data('val') + ' -- ' + $(this).val() + key );});//set the `data-val` attribute for the second textarea$('.two').data('val', '').on('focus', function () { //when this textarea is focused, return its value to the remembered data-attribute this.value = $(this).data('val');}).on('change', function () { //when this textarea's value is changed, set it's data-attribute to save the new value //and update the textarea with the value of the first one $(this).data('val', this.value); this.value = this.value + ' -- ' + $('.one').val();});


