Javascript sending key codes to a lt;textareagt; element(Javascript 将密钥代码发送到 lt;textareagt;元素)
问题描述
我不知道如何在 textarea 元素上触发 keydown 事件,例如想象一下我有两个 textarea 元素,当我在第一个中输入内容时,我希望第二个框也显示输入,但由于某种原因,我必须通过事件来完成.这是我尝试过的,但它不起作用:
I can't figure out how to trigger a keydown event on a textarea element, e.g. imagine i have two textarea elements and when i type something in the first one, I want the second box to show the typing as well, but for a certain reason I have to do it via events. This is what I tried and it doesn't work:
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<textarea id='first'></textarea>
<textarea id='second'></textarea>
<script>
jQuery("#first").keydown(function(event)
{
var keydown = jQuery.Event("keydown")
keydown.keyCode = event.keyCode
keydown.which = event.which
jQuery("#second").trigger(keydown)
})
</script>
有什么想法可以实现吗?
Any ideas how could I achieve that?
推荐答案
事件被发送,浏览器只是没有反应(即在文本区域中放置字符)
The event is sent, the browser just doesn't react to it (i.e., put characters in the textarea)
并非所有浏览器(据我所知)都允许您调度事件,而不仅仅是触发它们.但即使这样做也远非完美
Not all browsers (that I know of) allow you to dispatch events, not just trigger them. But even doing that is far from perfect
// Gecko only
$("#first").keypress(function(event)
{
var evt = document.createEvent('KeyEvents');
evt.initKeyEvent(
event.type
, event.bubbles
, event.cancelable
, event.view
, event.ctrlKey
, event.altKey
, event.shiftKey
, event.metaKey
, event.keycode
, event.charCode
);
$('#second')[0].dispatchEvent( evt );
});
试试这个例子,你就会明白我所说的它远非完美的意思.基本上,做你所要求的方式也是你说你做不到的方式 - 按价值.
Try this example and you'll see what I mean by how it's far from perfect. Basically, the way to do what you're asking is also the way you say you can't - by value.
但是,您可以将自定义数据与事件一起传递,从而得到如下所示的解决方案
However, you can pass custom data along with the event, which leads to a solution that looks like this
$("#first").bind( 'keyup change', function(event)
{
$('#second').trigger( 'mimic', $(this).val() );
});
$("#second").bind( 'mimic', function( event, value )
{
$(this).val( value );
})
这样就够了吗?
这篇关于Javascript 将密钥代码发送到 <textarea>元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript 将密钥代码发送到 <textarea>元素
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01