当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当用户编辑具有contentteditable属性的div的内容时,我想运行一个函数。onchange事件的等价物是什么?
我使用jQuery,所以使用jQuery的任何解决方案都是首选。谢谢!
当前回答
JQuery的一个简单的答案,我刚刚创建了这段代码,并认为它将对其他人也有帮助
var cont;
$("div [contenteditable=true]").focus(function() {
cont=$(this).html();
});
$("div [contenteditable=true]").blur(function() {
if ($(this).html()!=cont) {
//Here you can write the code to run when the content change
}
});
其他回答
这里有一个更有效的版本,它对所有可内容使用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
onchange事件不会在具有contentEditable属性的元素被更改时触发,建议的方法是添加一个按钮,以“保存”版本。
检查这个插件,它以这种方式处理问题:
创建一个快速的jQuery contentteditable插件
非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'))
该元素现在可以由用户编辑,直到失去焦点。
在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
}
}
在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例子