内容可编辑的更改事件 [英] contenteditable change events

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

问题描述

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

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

解决方案

我建议将侦听器附加到由可编辑元素触发的关键事件,尽管您需要注意 keydownkeypress 事件在内容本身改变之前被触发.这不会涵盖更改内容的所有可能方法:用户还可以使用编辑或上下文浏览器菜单中的剪切、复制和粘贴,因此您可能需要处理 cut copypaste 事件也是如此.此外,用户可以放置文本或其他内容,因此那里有更多事件(例如,mouseup).您可能希望轮询元素的内容作为后备.

2014 年 10 月 29 日更新

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

演示:

document.getElementById("editor").addEventListener("input", function() {console.log("输入事件触发");}, false);

<div contenteditable="true" id="editor">请在此处输入内容</div>

演示: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天全站免登陆