jquery 事件处理程序 - 根据特定键和操作触发函数

发布于 2024-08-26 19:41:07 字数 189 浏览 6 评论 0原文

背景故事:当用户用鼠标选择文本字段中的一部分文本(手动标记),然后点击“alt”键时,就会触发某个功能。

我的问题是:

  • 当 用户按下某个键(在她的键盘上)?
  • 如何保留所选文本的一部分并将其用作 该函数的参数?

我尝试在网上查找,但没有找到任何好的答案,但我也非常感谢链接。

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 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小伙你站住 2024-09-02 19:41:07
$(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; 
    } 
} 

如果您想获取文本输入或文本区域中选定的文本,您可以执行以下操作:

$(':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);
        }
    }
});
$(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);
        }
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文