当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当前回答
为了避免计时器和“保存”按钮,你可以使用blur事件,当元素失去焦点时触发。但是为了确保元素确实被改变了(不仅仅是聚焦和散焦),它的内容应该与它的上一个版本进行比较。或者使用keydown事件在这个元素上设置一些“脏”标志。
其他回答
这里有一个更有效的版本,它对所有可内容使用on。这是基于上面的答案。
$('body').on('focus', '[contenteditable]', function() {
const $this = $(this);
$this.data('before', $this.html());
}).on('blur keyup paste input', '[contenteditable]', function() {
const $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
});
项目在这里:https://github.com/balupton/html5edit
为了避免计时器和“保存”按钮,你可以使用blur事件,当元素失去焦点时触发。但是为了确保元素确实被改变了(不仅仅是聚焦和散焦),它的内容应该与它的上一个版本进行比较。或者使用keydown事件在这个元素上设置一些“脏”标志。
看看这个想法。 http://pastie.org/1096892
我觉得很接近了。HTML 5确实需要将更改事件添加到规范中。唯一的问题是回调函数在$(this). HTML()中内容实际更新之前计算if (before == $(this). HTML())。setTimeout不起作用,这很可悲。让我知道你的想法。
我构建了一个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();
如果您愿意,还可以删除/添加事件
两个选择:
1)对于现代(常青树)浏览器: “输入”事件将充当另一个“更改”事件。
https://developer.mozilla.org/en-US/docs/Web/Events/input
document.querySelector('div').addEventListener('input', (e) => {
// Do something with the "change"-like event
});
or
<div oninput="someFunc(event)"></div>
或(使用jQuery)
$('div').on('click', function(e) {
// Do something with the "change"-like event
});
2)考虑到IE11和现代(常青树)浏览器: 这将监视div中的元素变化及其内容。
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
var div = document.querySelector('div');
var divMO = new window.MutationObserver(function(e) {
// Do something on change
});
divMO.observe(div, { childList: true, subtree: true, characterData: true });