设置丢失 上的插入符号位置按 TAB 键时的元素
我的网页上有 pre
和 contentEditable="true"
,当我按 时,我试图让它附加
。我找到了一些其他插件,但它们仅适用于 "\t"
>
所以,问题是,当我通过 jQuery 将文本附加到
时,它会丢失插入符号位置。我确信它正在失去焦点,但事实并非如此。所以
$("pre").focus()
不会执行任何操作。
我首先尝试对其进行模糊处理,但这并不实际,因为插入符号将根据浏览器返回到不同的位置。请提供一些帮助...:P,
我的代码在这里: http://jsfiddle.net/parisk/kPRpj/
I have pre
with contentEditable="true"
on my webpage and I am trying to make it append "\t"
when I press <TAB>
. I found some other plugins for that but they were working only on <textarea>
.
So, the problem is that when I append text to the <pre>
through jQuery, it loses the caret position. I was sure it was losing focus but it's not. So $("pre").focus()
, will do nothing.
I tried to blur it first but this is not practical cause the caret will return on different position depending on the browser. some help please... :P,
My code is here: http://jsfiddle.net/parisk/kPRpj/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
document.execCommand
代替。 这是一个演示。简而言之:Try using
document.execCommand
instead. Here’s a demo. In short:首先尝试
插入一个选项卡。它会在你的光标后面插入一个制表符
chrome 中
,然后在 IE8 的
应该在最后得到插入符。
(一起)
编辑
添加一个测试来查看 lastChild 是否为 null 等也会更安全。另外,在 keydown 函数中,如果您多次使用,则
jQuery("pre")
最好是jQuery(this)
并放入变量中。 (这个例子就是但我太懒了)firstly Try
for inserting a tab. it will insert a tab after your cursor
then in chrome
in IE8
should get you caret at the end.
(all together)
EDIT
it would also be safer to add in a test to see if the lastChild is null and other such. Also in the keydown function
jQuery("pre")
would be better to bejQuery(this)
and put into a variable if you are using more than once. (which the example is but I'm too lazy)仅针对您的问题,jquery caret 库非常擅长封装不同浏览器(即 IE)的怪癖: http://plugins.jquery.com/plugin-tags/caret
您始终可以使用它来获取所有选项卡位置的索引,然后稍后清理它们...
To only your question, the jquery caret libraries are pretty good at encapsulating the quirks around the different browsers (namely IE): http://plugins.jquery.com/plugin-tags/caret
You could always just use this to get an index of all the tab positions and then clean them later...
James Khoury 的答案总是将插入符号放在
这是修复此问题的修改版本:http://jsfiddle.net/kPRpj/12/。
让
tab
缩进该行而不是在插入符位置添加tab
字符应该是相当简单的。为此,您可以替换为
I've put a version 在 jsfiddle 上以这种方式运行。但是,您可能需要解决
'\n\r'
管理中的一些不一致问题。例如,我看到 chromium 将每一行视为一个单独的文本节点,这是相当意外的。我没有在其他浏览器中测试过。James Khoury's answer always puts the caret at the end of the
<pre>
, which is not desirable when the user hitstab
in the middle of the text.Here is a modified version tha fixes this issue : http://jsfiddle.net/kPRpj/12/.
It should be fairly trivial to make
tab
indent the line instead of adding atab
character at the caret position. To do that, you would replacewith
I've put a version that behaves this way on jsfiddle. However you might need to work around some inconsistencies in their management of
'\n\r'
. For example, I see that chromium sees each line as a separate text node, which is rather unexpected. I haven't tested it in other browsers.