javascript - 使用 jQuery 在 contenteditable 元素上模拟按键

标签 javascript jquery keypress contenteditable simulate

如何以编程方式在可内容编辑的 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/

相关文章:

javascript - filereader 文件格式无法识别 json 和 geojson

javascript - Material Ui popover 不在正确的位置

javascript - 如何在单击主体和按钮 JS 时删除类

javascript - Fancybox,播放带有开始时间和自动播放的 YouTube 视频

c++ - 模拟全局热键

当触发 keyup 时,Javascript 会忘记其他 keydown

javascript - 复选框更改功能仅触发一次

javascript - 如何使用 v8 隐藏类优化技术进行优化?

javascript - 向上滚动到顶部时堆叠两个 div

javascript - 将图像元素移动到仅使用 Javascript 的位置 - 这是我的代码。