简体   繁体   English

如何使用Javascript / Jquery模拟在文本区域中的键入?

[英]How to simulate typing into a textarea using Javascript/Jquery?

I have a textarea which uses a jquery plugin to resize itself while the user types in it. 我有一个textarea,它在用户输入时使用jquery插件来调整自身大小。

The problem is, I want users to be able to edit things they've already typed. 问题是,我希望用户能够编辑他们已经键入的内容。 However since the textarea starts with 35 cols, 1 row, if the user had a long message he typed, then it doesn't completely show, only one line shows which cuts off. 但是,由于textarea以35列开始,为1行,因此,如果用户键入的内容很长,则不会完全显示出来,只有一行会被截断。

Is there a way to simulate a keypress event in that textarea, so that the text resizing will fire up and resize the textarea? 有没有一种方法可以模拟该文本区域中的按键事件,以便重新调整文本大小并调整文本区域的大小?

There's no way to programatically call the text resize function. 无法以编程方式调用文本调整大小功能。

Just trigger the keypress event on that textarea: 只需在该文本区域上触发按键事件:

$(function(){
     $('textarea').trigger('keypress');
}).

if there are multiple textareas, and you want to trigger the event on a specific textarea that has an id, of course the syntax becomes: 如果有多个文本区域,并且您想在具有ID的特定文本区域上触发事件,则语法自然变为:

$(function(){
     $('#myTextarea').trigger('keypress');
}).

If this is your own code, then you can just call your function 如果这是您自己的代码,那么您只需调用函数即可

Your text area likely already has some function that gets called on each keystroke. 您的文本区域可能已经具有一些可在每次击键时调用的功能。 The simplest way for you is then to call this same function when your page loads and that's it. 对于您来说,最简单的方法就是在页面加载时调用相同的函数。

<textarea onkeypress="someFunc();" />

just call this someFunc when page loads and it should do the same thing as if you pressed a key. 只需在页面加载时调用此someFunc ,它就可以执行与按键相同的操作。

Not written by you? 不是您写的吗? Using third party plugins then 然后使用第三方插件

If you're using some sort of a jQuery plugin (not your own) then you should check whether it provides this functionality to initially set text area's size. 如果您使用某种jQuery插件(不是您自己的),则应检查它是否提供此功能来初始设置文本区域的大小。 If it doesn't then I suggest you switch to a different plugin that does that. 如果没有,那么我建议您切换到执行此操作的其他插件。 Or write your own if you know how. 如果您知道怎么写,也可以自己写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM