可以理解的变化事件 [英] contenteditable change events

查看:175
本文介绍了可以理解的变化事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户使用 contenteditable 属性编辑 div 的内容时运行一个函数。什么是 onchange 事件?



我使用jQuery,因此任何使用jQuery的解决方案都是首选。谢谢!

解决方案

我建议将侦听器附加到可编辑元素触发的关键事件,尽管你需要知道<在内容本身发生更改之前触发code> keydown 和 keypress 事件。这不会涵盖更改内容的所有可能方法:用户还可以使用剪辑,复制和粘贴从编辑或上下文浏览器菜单,因此您可能需要处理 cut 复制粘贴事件。另外,用户可以放弃文本或其他内容,因此在那里有更多事件(例如, mouseup )。您可能希望轮询元素的内容作为后备。



更新2014年10月29日



HTML5 输入

code>事件是长期的答案。在撰写本文时,它支持当前Mozilla(来自Firefox 14)和WebKit / Blink浏览器中的 contenteditable 元素,但不支持IE。



演示:

  document.getElementById(editor)。addEventListener(input,function(){console.log(input event fired);},false);  

请输入以下内容< / div>

/ code>



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


I want to run a function when a user edits the content of a div with contenteditable attribute. What's the equivalent of an onchange event?

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

解决方案

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. 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. Also, the user can drop text or other content, so there are more events there (mouseup, for example). You may want to poll the element's contents as a fallback.

UPDATE 29 October 2014

The HTML5 input event is the answer in the long term. At the time of writing, it is supported for contenteditable elements in current Mozilla (from Firefox 14) and WebKit/Blink browsers, but not 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/

这篇关于可以理解的变化事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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