如何知道插入符号是否位于textarea中的最后一个字符?(How to know if caret resides in the last character in textarea?)

编程入门 行业动态 更新时间:2024-10-04 23:32:18
如何知道插入符号是否位于textarea中的最后一个字符?(How to know if caret resides in the last character in textarea?)

我有一个可编辑的表,如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.

更多推荐

本文发布于:2023-07-09 10:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085563.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:符号   字符   textarea   character   caret

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!