如何在contenteditable中跟踪插入符/光标? [英] How to track caret/cursor in contenteditable?

查看:91
本文介绍了如何在contenteditable中跟踪插入符/光标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想跟踪插入符号/光标的移动。不过我不知道最好的方法是什么。

I'd like to track the movement of the caret/cursor in a contenteditable. I'm not sure what's the best way to do this, though.

我正在听点击,keydown,keyup。 (按键当然甚至不会触发箭头键或ctrl-x之类的东西。)

I'm currently listening for click, keydown, keyup. (keypress of course doesn't even fire for things like arrow keys or ctrl-x.)

虽然点击工作正常,但keydown的问题是它在之前被解雇了插入符实际上是移动的,所以当我查询当前文档选择范围时,我得到旧位置而不是新位置。但是,如果我依靠keyup来获取更新的位置,它会触发太晚:按下按键时插入符号就会移动,但是键会在任意时间后释放。

While click works fine, the problem with keydown is that it's fired before the caret actually moves, so when I query the current document selection range, I get the old position and not the new one. But if I rely on keyup to get the updated position, it fires too late: the caret moves as soon as the key is pressed down, but the key is released an arbitrary time later.

这一定是可能的,因为CKeditor之类的东西能够做到这一点。任何提示?

This must be possible because things like CKeditor are able to do this. Any hints?

推荐答案

很高兴看到人们在谈论CKEditor :)。我是其开发人员之一,我没有在选择方面做太多工作,但我会尽力帮助。

It's nice to read that people are talking about CKEditor :). I'm one of its developers and I haven't been working much on selection, but I'll try to help.

我所知道的是我们有内部 selectionChange 事件。那么我们什么时候检查它是否改变了? ......每200ms至少一次:)见:

What I know is that we've got an internal selectionChange event. So when do we check if it changed? ... ... At least once per every 200ms :) See:

http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/selection/plugin.js#L39

每当我们知道它可能已被更改时我们也检查选择(例如通过API或keyup / mouseup或本地选择更改 - http://dev.ckeditor.com/browser/CKEditor/trunk/ _source /插件/选择/ plugin.js#L554 )。所以...几乎所有的时间:) AFAIK我们做一些技巧,所以它不会烧掉你的CPU,但它仍然很重。但是,如果我们这样做,那么这是唯一可行的方法让这个工作得非常好。

We also check selection every time we know that it could have been changed (e.g. by the API or on keyup/mouseup or on native selectionchange - http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/selection/plugin.js#L554). So... pretty much all the time :) AFAIK we do some tricks, so it doesn't burn your CPU, but it's still heavy. However, if we did this, then it's the only possible way to have this working so nicely.

不幸的是,选择处理到目前为止最差在wysiwygs世界的任务。它在所有新旧浏览器中都如此破碎。我上面链接的文件中超过75%的LOC是黑客和技巧。这完全是疯狂的。

Unfortunately, selection handling is by far the worst task in wysiwygs world. It's so broken in all - old and new browsers. More than 75% LOC in the file I linked above are hacks and tricks. That's complete madness.

这篇关于如何在contenteditable中跟踪插入符/光标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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