如何检查光标是否在textarea内的空行? [英] How to check if cursor is on an empty line inside textarea?

查看:72
本文介绍了如何检查光标是否在textarea内的空行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查光标是否位于textarea内的空行?

How do I check if the cursor is on an empty line inside a textarea?

我不关心自动换行。我关心通过点击 Enter 创建的行。

I don't care about word wrapping. I care about lines that were created by hitting Enter.

$('textarea').on("change keyup", function() {
  if (cursor is on an empty line or the the line has just spaces) {
    console.log("empty");
  } else {
    console.log("has stuff");
  }
});

例如:


这会记录有东西

This would log "has stuff"

上面的行会记录空,这一行会记录有东西

The line above would log "empty" and this line would log "has stuff"


推荐答案

以下应该可以工作,但不会在旧版IE中使用。

The following should work, but won't in older versions of IE.

// on(..., function() {
if( this.value.substr(0,this.selectionStart).match(/(?:^|\r?\n\s*)$/)
 && this.value.substr(this.selectionStart).match(/^(?:\s*\r?\n|$)/)) {
    console.log("empty");
}

编辑搜索现在显式查找换行符,并且可选择更多空格。

EDIT search now explicitly looks for a newline, with further whitespace optional.

这篇关于如何检查光标是否在textarea内的空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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