我有一个可编辑的表,如excel one,我正在进行keydown处理以切换到下一个单元格。
假设我有以下单元格与插入符号高亮:
This is a text|在上面的示例中,插入符号位于最后一个字符处,因此如果用户按下键盘上的右键,我需要将单元格编辑器切换到下一个单元格。
我的问题是我怎么知道插入符号位于keydown事件处理程序中的textarea中的最后一个字符?
I have an editable table like excel one and I'm making keydown handling for switching to next cell.
Let's say I have the following cell with caret highlited:
This is a text|In the example above the caret resides at last character so if an user press right key on the keyboard I need to switch cell editor to next cell.
My question is how do I know that caret is resides at last character in textarea in keydown event handler?
最满意答案
由于您总是要检查最后一个字符,您可以在每个keydown上获取textarea value的length属性,并将length与textarea的selectionEnd属性进行比较:
selectionEnd - 指定或返回当前元素中所选文本的结束位置。
例:
document.getElementById("textAreaIdHere").onkeydown = function(){ // Get length of textarea value var len = this.value.length; // If character entered is at the end of the textarea (therefore cursor) if(this.selectionEnd === len) { // Is at the end } }jsFiddle在这里
selectionEnd仅适用于IE9 +。 为了在旧版浏览器中实现此功能,可以使用此垫片 。
As you're always going to be checking for the last character, you could grab the length property of the textarea value on every keydown and compare the length with the textarea's selectionEnd property:
selectionEnd - Specifies or returns the end position of the selected text within the current element.
Example:
document.getElementById("textAreaIdHere").onkeydown = function(){ // Get length of textarea value var len = this.value.length; // If character entered is at the end of the textarea (therefore cursor) if(this.selectionEnd === len) { // Is at the end } }jsFiddle here
selectionEnd is only available to use as of IE9+. For implementing this feature in older browsers, this shim may be of use.
更多推荐
发布评论