使用Javascript注册“keydown”事件后,Textarea滞后 [英] Textarea lags after registering `keydown` events using Javascript

查看:329
本文介绍了使用Javascript注册“keydown”事件后,Textarea滞后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将一堆代码附加到 onkeydown 事件中,但是继续输入文本到 textarea 快而清脆任何超过几个IF语句似乎都会相当缓慢。

How does one go about attaching a bunch of code to an onkeydown event, but keep entering text into a textarea fast and crisp? Anything more than a couple of IF statements seems to slow it down quite considerably.

编辑:我应该添加(不能相信我忘了!)这不影响桌面浏览器。这主要是iPhone Safari的一个问题。其他移动浏览器也可能受到影响,但是我们专注于iPhone Safari,因为它执行JS最好(AFAIK)

EDIT: I should add (can't believe I forgot!) that this doesn't affect desktop browsers. It's mainly an issue with iPhone Safari. Other mobile browsers might be affected as well, but we're focusing on iPhone Safari since it executes JS the best (AFAIK)

推荐答案

考虑到您的编辑关注于iPhone访问...

Considering your edit regarding this being focused on iPhone access...

iPhone真的没有那么多的力量。只要使用 onchange onblur 而不是 onkeydown

The iPhone really just doesn't have that much power to it. You'll be better off just using onchange or onblur instead of onkeydown.

Dave的答案的替代方法是等待用户暂停(例如5秒钟):

An alternative to Dave's answer is waiting for the user to pause (e.g. for 5 seconds):

var textarea = document.getElementById('textarea');

function checkTextArea() {
   if (textarea.value /* ... */) {
     /* ... */
   }
}

textarea.keyDownTimeout = null;
textarea.onkeydown = function () {
  if (textarea.keyDownTimeout) clearTimeout(textarea.keyDownTimeout);
  textarea.keyDownTimeout = setTimeout(checkTextArea, 5000);
};

这应该使用第一个按键设置定时器,停止并重新创建每个连续按键的定时器。最后在用户停止输入后5秒钟打电话。

This should set the timer with the first keydown, stopping and recreating the timer for each successive keydown. Finally calling 5 seconds after the user stops typing.

另外,请注意 checkTextArea 之后没有括号。这将给出 setTimeout 函数的引用与其返回

Also, note the lack of parenthesis after checkTextArea. This will give setTimeout the function's reference vs. its return.

您还可以在功能中设置此功能,以便更容易使用多个元素:

You can also set this up in a function to make it easier to use for multiple elements:

function setPauseTimer(element, timeout, callback) {
  var timer = null;
  element.onkeydown = function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(function(){ callback(element); }, timeout);
  };
}

function checkTextArea(textarea) { /* moved from global to argument */
   if (textarea.value /* ... */) {
     /* ... */
   }
}

setPauseTimer(document.getElementById('textarea'), 5000, checkTextArea);

这篇关于使用Javascript注册“keydown”事件后,Textarea滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆