如何创建HTML5单行contentEditable选项卡,它侦听Enter和Esc [英] How to create a HTML5 single line contentEditable tab which listens to Enter and Esc

查看:82
本文介绍了如何创建HTML5单行contentEditable选项卡,它侦听Enter和Esc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作中的仪表板,我希望人们能够更改选项卡上的文本,以便创建最适合他们的类别。

I have a dashboard at work and I want people to be able to change the text on the tabs in order to create categories which fit them best.

我想要单行文本,将忽略 Esc 上的更改或在 Enter Blur

I wanted single line text which would disregard changes on Esc or commit the changes on Enter or Blur.

我找到了答案,但认为我会发布以帮助他人。

I found the answer but figured I would post in order to help others.

推荐答案

以下是HTML标记:

<span contenteditable="false"></span>

这是jQuery / javascript:

Here is the jQuery/javascript:

$(document).ready(function() {
    $('[contenteditable]').dblclick(function() {
        $(this).attr('contenteditable', 'true');
        clearSelection();
        $(this).trigger('focus');
    });

    $('[contenteditable]').live('focus', function() {
        before = $(this).text();
        if($(this).attr('contenteditable') == "true") { $(this).css('border', '1px solid #ffd646'); }
    //}).live('blur paste', function() {
    }).live('blur', function() {
        $(this).attr('contenteditable', 'false');
        $(this).css('border', '1px solid #fafafa');
        $(this).text($(this).text().replace(/(\r\n|\n|\r)/gm,""));

        if (before != $(this).text()) { $(this).trigger('change'); }
    }).live('keyup', function(event) {
        // ESC=27, Enter=13
        if (event.which == 27) {
            $(this).text(before);
            $(this).trigger('blur');
        } else if (event.which == 13) {
            $(this).trigger('blur');
        }
    });

    $('[contenteditable]').live('change', function() {
        var $thisText = $(this).text();
        //Do something with the new value.
    });
});

function clearSelection() {
    if ( document.selection ) {
        document.selection.empty();
    } else if ( window.getSelection ) {
        window.getSelection().removeAllRanges();
    }
}

希望这对某人有帮助!

这篇关于如何创建HTML5单行contentEditable选项卡,它侦听Enter和Esc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆