2014-01-07 39 views
1

如何檢查光標是否位於textarea內的空行上?如何檢查遊標是否在textarea內的空行上?

我不在乎單詞包裝。我關注通過點擊輸入創建的線條。

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

例如:

這將日誌 「有東西」

線上面會記錄 「空」 與這條線將日誌 「有東西」

+0

因爲我知道JavaScript是不可能的 – gogagubi

+0

一個空行可能是由於包裝和CR/LF生成的。你關心哪個? –

+0

我能想到的唯一方法(計算字符數)取決於瀏覽器在textarea中使用等寬字體,這不能再保證。 – Blazemonger

回答

1

以下應該工作,但不會在舊版本的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"); 
} 

編輯搜索現在明確地尋找一個換行符,進一步空白可選。

+0

這裏指的是'this',textarea的值是什麼? –

+0

它指的是事件綁定的元素。在這種情況下,textarea本身。 –

+0

其實,從頭開始。如果textarea有任何文本,它將不會工作:/ –