简体   繁体   English

使用输入类型=按钮通过jQuery的“ Ctrl + B”功能

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

I am trying to build an blog writing textbox, in which I am using a div element (contenteditable="true"). 我正在尝试构建一个博客编写文本框,其中使用了div元素(contenteditable =“ true”)。 I am placing buttons for Bold, Italic,etc at the bottom. 我在底部放置了粗体,斜体等按钮。 I want to trigger 'Ctrl+B' event when clicked on 'Bold' button and 'Ctrl+I' while clicked on 'Italic'. 我想在单击“粗体”按钮时触发“ Ctrl + B”事件,而在单击“斜体”时触发“ Ctrl + I”事件。 I have written following snippet for this functionality, but I am not getting the expected results. 我已经为该功能编写了以下代码段,但没有得到预期的结果。 Can anybody put some thought on this? 有人可以考虑一下吗?

$('#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);
});

The way you make these changes to a contenteditable element is via document.execCommand contenteditable元素进行这些更改的方法是通过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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM