onkeyup、onkeydown 事件未针对 SPAN 元素触发 [英] onkeyup, onkeydown events not firing for SPAN element

查看:43
本文介绍了onkeyup、onkeydown 事件未针对 SPAN 元素触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下两个 span 元素:1) contenteditable div 中的元素.2) contenteditable 元素.

I've defined the following two span elements: 1) element inside a contenteditable div. 2) contenteditable element.

到目前为止,我无法为我的第一个案例 () 触发 onkey 事件.对于不在 contenteditable div 内的第二个 (),这些事件可以正常触发.

So far, I can't get the onkey events to fire for my first case (). For the second one () which is not inside a contenteditable div, these events fire fine.

有人知道为什么吗?

示例代码如下:

<div id='editor' contenteditable>
div contents...
<span id='span1' style="background-color:red"  onkeyup='alert("span1 keyup");' onkeypress='alert("span1 keypress");' onkeydown='alert("span1 keydown");'>Hello</span>
</div>

<span contenteditable id='span2' style="background-color:yellow" onkeyup='alert("span2 keyup");' onkeypress='alert("span2 keypress");' onkeydown='alert("span2 keydown");'>World</span>

http://jsfiddle.net/nr9HG/

推荐答案

我遇到了同样的问题,如果您将可编辑的跨度放在另一个不可编辑的跨度中,它似乎可以工作:

I had the same problem and it seems to work if you put your editable span inside another non-editable span :

<div id="editor" contenteditable="true">div contents...
    <span contenteditable="false>
        <span id='span1' contenteditable="true" style="background-color:red"  onkeyup='alert("span1 keyup");' onkeypress='alert("span1 keypress");' onkeydown='alert("span1 keydown");'>Hello</span>
    </span>
</div>

您将能够在编辑器 div 和 span1 中捕获 keydown/keyup 事件.

You will be able to catch keydown/keyup events both on the editor div AND in your span1.

您需要内部跨度有焦点来捕捉来自它的 keydown 事件.使用 DOM 方法 .focus() 来做到这一点.

you need the inner span to have the focus to catch keydown events coming from it. Use the DOM method .focus() to do so.

这篇关于onkeyup、onkeydown 事件未针对 SPAN 元素触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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