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
180 views
in Technique[技术] by (71.8m points)

javascript - 可编辑的变更事件(contenteditable change events)

I want to run a function when a user edits the content of a div with contenteditable attribute.

(当用户使用contenteditable属性编辑div的内容时,我想运行一个函数。)

What's the equivalent of an onchange event?

(什么是onchange事件?)

I'm using jQuery so any solutions that uses jQuery is preferred.

(我使用的是jQuery,因此首选使用jQuery的解决方案。)

Thanks!

(谢谢!)

  ask by Jourkey translate from so

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

1 Answer

0 votes
by (71.8m points)

I'd suggest attaching listeners to key events fired by the editable element, though you need to be aware that keydown and keypress events are fired before the content itself is changed.

(我建议将侦听器附加到由editable元素触发的按键事件上,尽??管您需要知道在更改内容本身之前会触发keydownkeypress事件。)

This won't cover every possible means of changing the content: the user can also use cut, copy and paste from the Edit or context browser menus, so you may want to handle the cut copy and paste events too.

(这不会涵盖更改内容的所有可能方法:用户还可以从“编辑”或上下文浏览器菜单中使用剪切,复制和粘贴,因此您可能也想处理cut copypaste事件。)

Also, the user can drop text or other content, so there are more events there ( mouseup , for example).

(同样,用户可以放置文本或其他内容,因此在那里有更多事件(例如mouseup )。)

You may want to poll the element's contents as a fallback.

(您可能希望轮询元素的内容作为后备。)

UPDATE 29 October 2014

(2014年10月29日更新)

The HTML5 input event is the answer in the long term.

(从长远来看, HTML5 input事件就是答案。)

At the time of writing, it is supported for contenteditable elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not IE.

(在撰写本文时,当前Mozilla(来自Firefox 14)和WebKit / Blink浏览器中的contenteditable元素均支持该功能,但IE不支持。)

Demo:

(演示:)

 document.getElementById("editor").addEventListener("input", function() { console.log("input event fired"); }, false); 
 <div contenteditable="true" id="editor">Please type something in here</div> 

Demo: http://jsfiddle.net/ch6yn/2691/

(演示: http//jsfiddle.net/ch6yn/2691/)


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

...