问题
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