事件捕获与使用contentEditable div冒泡 [英] Event capturing vs. bubbling with a contentEditable div

查看:248
本文介绍了事件捕获与使用contentEditable div冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个内容可编辑的div,我需要处理在将该字符添加到div之前和之后捕获按键的操作.

I am dealing with a content editable div and I need to deal with capturing key strokes both before and after the character has been added to the div.

我对捕获与冒泡的理解是,该事件首先在dom树中被捕获,然后向下传递,而对于冒泡,它从最低层开始并在树上冒泡.

My understanding of capturing vs. bubbling is that the event gets captured at the highest level in the dom tree first then passes it down, while for bubbling it starts at the lowest level and bubbles up the tree.

基于这种理解,我认为,如果在捕获阶段添加了事件侦听器,则可编辑div的内容将反映出发送击键之前 的文本.如果我在冒泡阶段添加了事件侦听器,则div的文本内容将包含我刚刚键入的字符.

Based on that understanding, I thought that if I added an event listener at the capturing phase, the content of the editable div would reflect the text from before the keystroke had been sent. If I add an event listener at the bubbling phase, the div's text content will contain the character I just typed.

事实并非如此:无论是在捕获阶段还是冒泡阶段添加事件侦听器,div的内容都不会包含最近输入的字符.

This doesn't seem to be the case though: whether the event listener is added at the capturing or bubbling phase, the div's content never includes the most recently typed character.

这是一个简单的测试用例,可以尝试一下:

Here is a simple test case to try it out:

<div id="captureTest" contentEditable='true' style='height: 30px; width: 400px; border-style:solid; border-width:1px'></div>

<script type="text/javascript">
    var div = document.getElementById('captureTest');
    div.addEventListener("keydown", function() {alert('capture: ' + this.innerHTML)}, true);
    div.addEventListener("keydown", function() {alert('bubble: ' + this.innerHTML)}, false);
</script>

我希望第二个函数的输出在键入字符后包含div的新文本,但这似乎并非如此.

I would expect the output of the second function to include the div's new text after typing a character, but this doesn't seem to be the case.

我的问题是:是否有一种方法可以从内容可编辑的div中捕获击键事件并获取键入键后 的内容?我需要这个来实现预输入功能.

My question is: is there a way to capture a keystroke event from a content editable div and get the content as it will be after the key is typed? I need this for implementing typeahead functionality.

我知道我可以停止事件,然后使用executeCommand('insertHTML'),但这在处理删除,退格,粘贴和其他类型的插入时会崩溃,所以这不是解决方案.

I know that I can stop the event and then use executeCommand('insertHTML'), but this breaks down when handling deletions, backspaces, pastes and other types of insertions, so that is not a solution.

我正在Firefox 3中对此进行测试.我知道IE没有addEventListener方法.

I am testing this in Firefox 3. I know that IE doesn't have an addEventListener method.

谢谢您的建议!

推荐答案

您需要2个不同的回调,一个用于 keydown ,另一个使用 keyup keypress (仅当元素同时注册keydown和keyup时才触发).

You need 2 different callbacks, one for keydown and another with keyup or keypress (which is only fired when the element registered both the keydown + keyup).

这篇关于事件捕获与使用contentEditable div冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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