如何以编程方式在可内容编辑的 div 中模拟按键?
我想使用 jQuery 脚本以编程方式删除字符,无需任何人工输入。
我想通过在 contenteditable div 中模拟退格键来删除 span 标签末尾的一些字符。
<div class="editor" contenteditable="true">
<span>This is a span!!</span>
</div>
所以结果会是这样的:
This is a span
我不想重写文本。我需要模拟退格键。使用此代码进行测试,但没有任何反应。
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
$('.editor').trigger(jQuery.Event('keypress', { keycode: 8 }));
});
你能帮帮我吗?
最佳答案
我使用了评论中提到的部分代码:SO answer - Yuri
这里是触发keydown事件的部分
$(document).ready(function(){ // after the website loaded
// I want to trigger a keypress (backspace key)
// inside of the contenteditable div Programatically
var e = jQuery.Event("keydown");
e.which = 8; // backspace key
$(".editor").trigger(e);
});
之后,我为 .editor 元素创建了一个处理程序
$(".editor").keydown(function(e) {
if (e.originalEvent === undefined) {
console.log('triggered programmatically');
} else {
console.log('triggered by the user');
}
console.log("Key pressed:" + e.which);
if(e.which == 8) {
// do your stuff
}
});
我还放置了一个验证器来检查事件是由用户还是以编程方式触发的。
关于javascript - 使用 jQuery 在 contenteditable 元素上模拟按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48662705/