'Ctrl+B'使用inputtype=按钮通过jQuery实现功能

'Ctrl+B' functionality through jQuery using input type=button

本文关键字:jQuery 功能 实现 Ctrl+B 使用 inputtype 按钮      更新时间:2023-09-26

我正在尝试构建一个博客写作文本框,在其中我使用了一个div元素(contenteditable="true")。我正在底部放置粗体、斜体等按钮。我想在单击"粗体"按钮时触发"Ctrl+B"事件,在单击"斜体"时触发"Ctrl+I"事件。我已经为此功能编写了以下代码段,但没有得到预期的结果。有人能想一想吗?

$('#bold').mousedown(function(){
    var e = jQuery.Event("keydown");
    e.ctrlKey= true;
    e.which = 66; 
    e.keyCode=66;
    $('#displayBox').trigger(e);
    $('#displayBox').focus();
});
$('#bold').mouseup(function(){
    $('#displayBox').focus();
    var e = jQuery.Event("keyup");
    e.ctrlKey= false;
    e.which = 66;
    e.keyCode=66;
    $('#displayBox').trigger(e);
});

内容可编辑元素进行这些更改的方式是通过document.execCommand

var box = document.getElementById('displayBox');
document.getElementById('bold').addEventListener('click', function (e) {
    box.focus(); // make it the active element so the command is applied to it
    document.execCommand('bold', false, null); // apply command
});

DEMO