How to check if cursor is on an empty line inside textarea?

倖福魔咒の 提交于 2019-12-11 02:54:17

问题


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

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");
  }
});

For example:

This would log "has stuff"

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


回答1:


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.



来源:https://stackoverflow.com/questions/20980870/how-to-check-if-cursor-is-on-an-empty-line-inside-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!