Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Listening to events of a contenteditable HTML element

I'm trying to figure out if there is any way to listen to events like focus or change of an HTML element with contenteditable attribute.

I have this html markup:

<p id="test" contenteditable >Hello World</p>

I've tried these without any success(JSBin):

var test = document.querySelector('#test');
test.addEventListener('change', function(){
  alert('content edited');
}, false);
test.addEventListener('DOMCharacterDataModified', function(){
  alert('content edited');
}, false);
test.addEventListener('focus', function(){
  alert('content edited');
}, false);

I don't want to listen to keyboard or mouse events. I didn't find any clear documentation in W3C and MDN about contenteditable.

Is it possible to listen to change and focus or other events on a content editable HTML element?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Not really. There is no change event for contenteditable elements, and there's no HTML5 input event either, although I think that will eventually appear. It's a pain.


UPDATE 23 June 2012

Recent WebKit supports the HTML5 input event on contenteditable elements, as does Firefox 14.


focus, however, does work, as does DOMCharacterDataModified in most browsers (though notably not IE < 9). See http://jsfiddle.net/UuYQH/112/

By the way, contenteditable is not a Boolean attribute: it requires a value, which should be one of "true", "false", "inherit" and the empty string (which is equivalent to "true").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...