Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

javascript - onkeyup, onkeydown events not firing for SPAN element

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

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.

Does anybody knows why?

Here's the example code:

<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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...