开发者

jquery event handler- trigger function upon specific key and action

Background story: when a user selects a portion of text in a text field with her mouse (mark it up manually), and subsequently hits "alt" key, a certain function would trigger.

My questions are:

  • How can I trigger a function when a user hits a key (in her keyboard)?
  • How开发者_StackOverflow中文版 can I preserve a portion of text selected, and use it as a parameter for that function?

I've tried looking up online but haven't found any good answers, but i'd greatly appreciate links as well.


$(document).keydown(function(event){
    if (event.altKey) {
        var text = $.trim(getSelectedText());
        if (text.length) {
            console.log(text);
        }
    }
});

function getSelectedText() { 
    if (window.getSelection) { 
        return window.getSelection().toString(); 
    } else if (document.getSelection) { 
        return document.getSelection(); 
    } else if (document.selection) { 
        return document.selection.createRange().text; 
    } 
} 

If you want to get the selected text in a text input or textarea you can do this:

$(':text, textarea').keydown(function(event){
    if (event.altKey) {
        var text = '';
        if ('selectionStart' in this){
            var length = this.selectionEnd - this.selectionStart;
            text = $.trim($(this).val().substr(this.selectionStart, length));
        } else if (document.selection) {
            text = $.trim(document.selection.createRange().text);
        }
        if (text.length) {
            console.log(text);
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜