使用window.getSelection从textarea中获取选定的或光标位于的文本行 [英] use window.getSelection get selected or cursor located text line from textarea

查看:1305
本文介绍了使用window.getSelection从textarea中获取选定的或光标位于的文本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ajax调用动态填充textarea。在我的代码中,我想使用window.getSelection获取游标的当前行内容。我尝试了下面的代码,

var range = window.getSelection()。toString;

alert(typeof(range) );



但是,它将alert函数作为alert消息返回。或者任何其他更好的方法,从代码需要在所有浏览器中支持的textarea中获取光标的当前行内容。一旦我得到当前行内容,我会找出行号并更新其上的新内容。首先,textareas与常规内容有不同的选择API: selectionEnd >属性,而不是 window.getSelection()

其次,获取当前如果您要对浏览器的内容进行自动换行,则需要一些创意编码。我在堆栈溢出中看到了一些关于这个问题。这里有一个例子:

找到换行在textarea文字环绕的阿拉伯文字


I am dynamically filling textarea using Ajax call's. In my code, I want to get the cursor's current line content using window.getSelection. I tried following code,

var range = window.getSelection().toString;
alert (typeof(range));

But, It returns function as alert Message. or Any other better way, to get the cursor's current line content from textarea that code need to support in all browser's.? Once I get the current line content I will find out line number and update new content on it.

解决方案

Firstly, textareas have a different selection API from regular content: use selectionStart and selectionEnd properties of the textarea rather than window.getSelection().

Secondly, getting the current line requires some creative coding if you're accounting for the browser's auotmatic wrapping of content. I've seen a few questions about this in Stack Overflow. Here's one example:

finding "line-breaks" in textarea that is word-wrapping ARABIC text

这篇关于使用window.getSelection从textarea中获取选定的或光标位于的文本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆