javascript - 当插入符在 textarea 中的行之间移动时触发事件

标签 javascript events textarea

如果用户更改插入符号所在的行,例如通过单击或使用向上/向下箭头,是否有办法让 textarea 触发事件?或者这在 Javascript 中是不可能的?我找到了查找/设置插入符当前位置的方法,但这不是我需要的...

最佳答案

听起来您需要为您的文本区域注册几个事件。在我的脑海中,一个点击事件和一个具有多个键码值的按键事件。您需要使用纯 javascript,还是有一些 javascript 库可供使用?

注册事件需要帮助吗?或者您是否需要帮助在其中一个事件中找到插入符号的位置? (请参阅安迪的链接)或者我的两个问题的答案都是"is"?


编辑

好吧,从你的评论来看,你对 jquery 没问题,而且 fieldselection 插件可以防止你重新发明轮子。

  1. 识别任何键盘键、鼠标点击、?复制粘贴?可以在文本字段中移动插入符号的事件。 Navigate and select portions of text, wikipedia
  2. 在事件期间,使用 fieldselection 插件获取新的插入符号位置。
  3. 使用当前插入符位置 && 字体大小 && 文本框物理大小 && 换行符计数来确定您是否已切换到新行。
  4. 如果您换行,触发自定义 jQuery 事件来完成您想要的工作。

//jQuery 1.7

$(document).ready(function(){
  var currentLine = -1;
  $("#textAreaID").on("keypress", function(evt){
   if(evt.which === 40 || ...){
//down arrow key, enter key, page down key, all will move the caret to a newline
     $(this).trigger("newline");
   }else{
//a ton of text in a fixed width textarea will move the cursor to a newline
     $(this).trigger("checkForNewline");
   }
  }).on("click checkForNewline", function(evt){
    var jqElem = $(this);
//fieldSelection plugin call
    var range = jqElem.getSelection();
    if(range["row"] && range["row"] !== currentLine){
      currentLine = range["row"];
      jqElem.trigger("newline");
   }else{
      var handTypedNewlines = jqElem.val().split(/\r\n|\r|\n/);
      var userTypedRowcounts = Math.floor(wholeString.length / jqElem.cols) + (handTypedNewlines instanceof 'object')?handTypedNewlines.length:0;
      if(userTypedRowcounts != currentLine){
         currentLine = userTypedRowcounts;
         jqElem.trigger("newline");
      }
   }
  }).on("newline", function(evt){
   // do your work, caret is on a newline.
  });
});

引用堆栈溢出。

reference to get .split() regex

关于javascript - 当插入符在 textarea 中的行之间移动时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170573/

相关文章:

javascript - Chart.js:使用折线图比较两个时期,例如 Google Analytics

javascript - 用正则表达式结果的修改版本替换正则表达式

c++ - AMQP-CPP - RabbitMQ 事件循环不工作

javascript - 如何使用循环 PHP 显示从表 Mysql 到 Textarea 字段的多个值

html - 将 textarea 包裹在 HTML 元素周围

javascript - 如何使文本区域成为 ACE 编辑器?

javascript - 需要改变元素在 slideToggle 上的位置

javascript - 如何根据上一个或下一个箭头为 nivo slider 提供特定的过渡效果?

python - Tkinter 应用程序中的日期更改通知 (win32)

actionscript-3 - as3中的EventListener和for循环