【问题标题】:Close Bootstrap popover on esc keypress在 esc 按键上关闭 Bootstrap 弹出窗口
【发布时间】:2014-08-30 20:24:45
【问题描述】:

我正在尝试使用 ESC 键关闭引导弹出窗口。

但是使用的时候好像不行:

$(document).keyup(function (event) {
    if (event.which === 27) {
        $('#example').popover('hide');
    }
});         

这是引导弹出窗口的小提琴:

http://jsfiddle.net/mashinista/b2NKt/

【问题讨论】:

标签: javascript jquery twitter-bootstrap


【解决方案1】:

您包含的小提琴具有弹出代码,但没有转义代码。

添加它,正如 koala_dev 指出的那样,你应该没问题:

Demo in fiddle

$('#example').popover();

$(document).keyup(function (event) {
    if (event.which === 27) {
        $('#example').popover('hide');
    }
});

另外,这与modal escape function works的方式非常相似

【讨论】:

【解决方案2】:

当工具提示在模态框内时会出现问题,因为 Esc 键应该会关闭模态框。如果用户只想关闭工具提示但随后整个模式关闭,则用户体验不佳。所以我建议,如果当前有要关闭的工具提示,那么用户将需要按 Esc 两次来关闭模式(第一次关闭工具提示),否则一次,就像往常一样。注意:这并不理想,尤其是对于屏幕阅读器用户而言,因此请将其作为进一步思考的食物。

/**
 * Accessibility: Close tooltips and popovers on ESC key (WCAG 1.4.13)
 * Note: Using event capture:true to cancel the propagation preventing the modal to close at first (hence no `.on()` here)
 * Tested with Bootstrap v3.4.1; Does not support IE 11
 */
$.fn.listenEscKeyToCloseOverlays = function () {
    return this.each(function () {
        if (("undefined" !== typeof $.fn.tooltip) || ("undefined" !== typeof $.fn.popover)) {
            document.addEventListener('keydown', function(e) {
                if ('Escape' === e.key) {
                    const $openTooltips = $('.tooltip');
                    const $openPopovers = $('.popover');

                    if ($openPopovers.length || $openTooltips.length) {
                        e.stopPropagation();
                        $openTooltips.tooltip('hide');
                        $openPopovers.popover('hide');
                    }
                }
            }, true);
        }
    });
};

$(document).listenEscKeyToCloseOverlays();

【讨论】:

    猜你喜欢
    • 2011-06-20
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多