收听Ctrl + B事件时,“书签”标签会显示

时间:2015-06-01 05:56:15

标签: javascript jquery html5 contenteditable

我正在尝试为contenteditable div实现 Ctrl + B ,这应该使文本变为粗体。

我遇到的唯一问题是,当按下 Ctrl + B 时,会出现浏览器的书签标签。

fiddle



$(document).ready(function() {
    $('#editable').designMode = 'on';
    $('#editable').on('keyup', function(e) {
        console.log(e.which);
        if(e.which == 66 && e.ctrlKey) {
            e.preventDefault();
            console.log('bold');
            document.execCommand ('bold', false, null);
            return false;
        }
    });
});

#editable {
    width:200px;
    height:100px;
    border:1px solid #999;
    border-radius: 3px;
    padding: 10px;
    box-sizing:border-box;
}

#editable:focus {
    outline: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div contenteditable="true" id="editable"></div>
&#13;
&#13;
&#13;

当我将注意力集中在可编辑的div中时,请帮我找到一种方法来禁用该书签。

1 个答案:

答案 0 :(得分:2)

检查此解决方案

jsFiddle

var g_state = 0;
$(document).ready(function() {
    $('body').keydown( function ( eve ) {
        if (eve.which === 17) {
            eve.preventDefault();
            g_state = 1;
        }
        return true;
    });
    $('body').keyup( function ( eve ){
        if (eve.which === 17) {
            eve.preventDefault();
            g_state = 0;
        }
        return true;
    });
    $('body').keypress( function ( eve ) {
        eve.preventDefault();
        if (eve.ctrlKey && (eve.which === 78)) {
            alert("(eve.ctrl + 'n')");   
        }
        else {
            if (g_state && (eve.which === 78)) {
                alert("(ctrl tracking by key up/down + 'n', resetting)");
                g_state = 0;
            }
            else {
                if (eve.shiftKey && (eve.which === 78)) {
                    alert("(eve.shift + 'n')");   
                }
                else {
                    alert("pass");   
                }
            }
        }
    });
});

嗨Dangling Cruze,

这里没有任何火箭科学,我们在这里做的是防止事件冒泡。并阻止事件到达Web浏览器。 如果事件是可取消的,则preventDefault()方法会取消该事件,这意味着不会发生属于该事件的默认操作。 单学期

例如,在以下情况下这可能很有用:

Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

At the document level we are binding all main three event 
    keydown
    keyup    
    keypress

and identifying key combination as well to prevent some key combination that is being used by browser as well. 

如果您需要任何进一步的帮助,请告诉我