当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当前回答
在MutationEvents下使用domcharacterdatmodified会导致同样的结果。超时设置是为了防止发送错误的值(例如,在Chrome中,我有一些空格键的问题)
var timeoutID;
$('[contenteditable]').bind('DOMCharacterDataModified', function() {
clearTimeout(timeoutID);
$that = $(this);
timeoutID = setTimeout(function() {
$that.trigger('change')
}, 50)
});
$('[contentEditable]').bind('change', function() {
console.log($(this).text());
})
JSFIDDLE例子
其他回答
我构建了一个jQuery插件来做到这一点。
(function ($) {
$.fn.wysiwygEvt = function () {
return this.each(function () {
var $this = $(this);
var htmlold = $this.html();
$this.bind('blur keyup paste copy cut mouseup', function () {
var htmlnew = $this.html();
if (htmlold !== htmlnew) {
$this.trigger('change')
}
})
})
}
})(jQuery);
你可以简单地调用$('.wysiwyg').wysiwygEvt();
如果您愿意,还可以删除/添加事件
在Angular 2+中
<div contentEditable (input)="type($event)">
Value
</div>
@Component({
...
})
export class ContentEditableComponent {
...
type(event) {
console.log(event.data) // <-- The pressed key
console.log(event.path[0].innerHTML) // <-- The content of the div
}
}
非JQuery回答…
function makeEditable(elem){
elem.setAttribute('contenteditable', 'true');
elem.addEventListener('blur', function (evt) {
elem.removeAttribute('contenteditable');
elem.removeEventListener('blur', evt.target);
});
elem.focus();
}
要使用它,调用(比如说)一个id="myHeader"的头元素
makeEditable(document.getElementById('myHeader'))
该元素现在可以由用户编辑,直到失去焦点。
考虑使用MutationObserver。这些观察器设计用于对DOM中的更改做出反应,并作为突变事件的性能替代品。
优点:
当发生任何变化时触发,这很难通过听其他答案所建议的关键事件来实现。例如,所有这些工作都很好:拖放,斜体,复制/剪切/粘贴上下文菜单。 设计时考虑到性能。 简单、直接的代码。比起监听10个事件的代码,理解和调试监听一个事件的代码要容易得多。 谷歌有一个优秀的突变摘要库,使得mutationobserver的使用非常简单。
缺点:
需要最新版本的Firefox (14.0+), Chrome(18+)或IE(11+)。 需要理解的新API 关于最佳实践或案例研究的信息还不多
了解更多:
我写了一个小片段来比较使用mutationobserver处理各种事件。我用了balupton的密码,因为他的答案得到了最多的好评。 Mozilla有一个关于API的优秀页面 看一下MutationSummary库
这个帖子在我调查这个主题的时候非常有帮助。
我把这里的一些代码修改成一个jQuery插件,这样它就可以以一种可重用的形式使用,主要是为了满足我的需求,但其他人可能更喜欢一个简单的界面来使用可满足的标记。
https://gist.github.com/3410122
更新:
由于其日益流行的插件已被Makesites.org采用
发展将从这里开始:
https://github.com/makesites/jquery-contenteditable