如果用户更改插入符号所在的行,例如通过单击或使用向上/向下箭头,是否有办法让 textarea 触发事件?或者这在 Javascript 中是不可能的?我找到了查找/设置插入符当前位置的方法,但这不是我需要的...
最佳答案
听起来您需要为您的文本区域注册几个事件。在我的脑海中,一个点击事件和一个具有多个键码值的按键事件。您需要使用纯 javascript,还是有一些 javascript 库可供使用?
注册事件需要帮助吗?或者您是否需要帮助在其中一个事件中找到插入符号的位置? (请参阅安迪的链接)或者我的两个问题的答案都是"is"?
编辑
好吧,从你的评论来看,你对 jquery 没问题,而且 fieldselection 插件可以防止你重新发明轮子。
- 识别任何键盘键、鼠标点击、?复制粘贴?可以在文本字段中移动插入符号的事件。 Navigate and select portions of text, wikipedia
- 在事件期间,使用 fieldselection 插件获取新的插入符号位置。
- 使用当前插入符位置 && 字体大小 && 文本框物理大小 && 换行符计数来确定您是否已切换到新行。
- 如果您换行,触发自定义 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.
});
});
引用堆栈溢出。
关于javascript - 当插入符在 textarea 中的行之间移动时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8170573/