在文本区域内:如果用户在空行上按 Enter 键,则捕获

发布于 2024-12-21 00:04:41 字数 176 浏览 4 评论 0原文

我知道这是一个奇怪的问题,但是:在文本区域内,我如何知道用户是否在 keydown 事件上按 Enter (e.keycode==13) 在空行

每次用户按下 Enter 时,我都必须触发特定的同步函数,除非用户只是为了好玩而添加新行(在这些情况下调用同步函数,将是对资源的严重浪费)。

I know this is kind of an odd question, but: Inside a textarea, how can I know if the user is pressing enter (e.keycode==13) on an empty line on the keydown event?

I have to trigger a specific sync function everytime the user presses enter except if the user is just adding new lines for fun (calling the sync function in those cases, would be a terrible waste of resources).

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

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

发布评论

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

评论(2

忱杏 2024-12-28 00:04:41

找到解决办法了!

$('#q').keydown(function(e){
    if(e.keyCode == 13) {
        if($(this).val()) {
            if($(this).val().substr($(this).getCursorPosition()-1,1).length) {
                //sync function here!
            } else {
                //user is pressing enter on empty line
            }
        }
    }
});

new function(a){a.fn.getCursorPosition=function(){var b=0;var c=a(this).get(0);if(document.selection){c.focus();var d=document.selection.createRange();var e=document.selection.createRange().text.length;d.moveStart("character",-c.value.length);b=d.text.length-e}else if(c.selectionStart||c.selectionStart=="0")b=c.selectionStart;return b}}(jQuery);

Found a solution!

$('#q').keydown(function(e){
    if(e.keyCode == 13) {
        if($(this).val()) {
            if($(this).val().substr($(this).getCursorPosition()-1,1).length) {
                //sync function here!
            } else {
                //user is pressing enter on empty line
            }
        }
    }
});

new function(a){a.fn.getCursorPosition=function(){var b=0;var c=a(this).get(0);if(document.selection){c.focus();var d=document.selection.createRange();var e=document.selection.createRange().text.length;d.moveStart("character",-c.value.length);b=d.text.length-e}else if(c.selectionStart||c.selectionStart=="0")b=c.selectionStart;return b}}(jQuery);
挽容 2024-12-28 00:04:41

嗯,这取决于他们最初是如何到达那里的。如果用户在整行上按 Enter 键,同步函数是否会被调用?如果是这样,那么他们如何才能到达空行呢?

Well, it depends on how they got there in the first place. If the user presses enter on a full line does the sync function get called? If so, then how do they ever get to an empty line?

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