当插入符号在textarea中的行之间移动时发射事件

Num*_*ats 10 javascript events textarea

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

Def*_*ity 3

听起来您需要为文本区域注册几个事件。我突然想到了一个点击事件和一个具有多个键码值的按键事件。您需要使用纯 JavaScript,还是有一些 JavaScript 库可以使用?

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


编辑

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

  1. 识别任何键盘按键、鼠标点击、“复制粘贴”?可以在文本字段中移动插入符号的事件。 导航并选择文本、维基百科的部分
  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.
  });
});
Run Code Online (Sandbox Code Playgroud)

引用堆栈溢出。

引用 get .split() 正则表达式