【问题标题】:Why focus is cleared after a click on the body为什么点击正文后焦点被清除
【发布时间】:2015-10-05 08:08:26
【问题描述】:

我在我的应用程序中使用 bootstrap、less 和 jQuery。我想问你关于元素的重点。

所以我有一个使用 ul li 锚点创建的项目列表。我已经完成了一个代码,使锚点在点击时被着色并在模糊时清除颜色。 问题是当用户点击身体的任何地方时,锚点的焦点被他自己清除了。

你知道它背后的问题是什么吗?

【问题讨论】:

  • 但据我了解,这是预期的行为。您能否提供简约示例来复制您的问题?
  • 你一直在用“专注”这个词——我不认为它意味着你认为它的意思......

标签: jquery twitter-bootstrap focus blur


【解决方案1】:

这是预期的行为。但是,如果由于某种原因您想在单击不可聚焦元素上的 body 上的任意位置时保持聚焦元素,则可以使用以下 sn-p:

//include IIFE if not already including jQuery UI
(function () {
    function focusable(element, isTabIndexNotNaN) {
        var map, mapName, img,
        nodeName = element.nodeName.toLowerCase();
        if ("area" === nodeName) {
            map = element.parentNode;
            mapName = map.name;
            if (!element.href || !mapName || map.nodeName.toLowerCase() !== "map") {
                return false;
            }
            img = $("img[usemap='#" + mapName + "']")[0];
            return !!img && $(img).is(':visible');
        }
        return (/^(input|select|textarea|button|object)$/.test(nodeName) ? !element.disabled :
            "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) &&
        // the element and all of its ancestors must be visible
        $(element).is(':visible');
    }
    $.extend($.expr[":"], {
        focusable: function (element) {
            return focusable(element, !isNaN($.attr(element, "tabindex")));
        }
    });
})();

$(':focusable').on('blur', function (e) {
    //using a timeout to put logic in event queue
    setTimeout(function () {
        if (!$(document.activeElement).is(':focusable')) this.focus();
    }.bind(this), 0);
});
/* for demo purpose only*/
a:focus {
    color: red;
    outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">anchor with href (focusable)</a>
<br/>
<a>anchor without href (unfocusable)</a>
<br/>
<input placeholder="input (focusable)" />
<div>div without tabindex (unfocusable)</div>
<div tabindex="0">div with tabindex (focusable)</div>
<div tabindex="-1">div with tabindex negative (focusable but untabbable)</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多