onBlur()不正常工作

3
我希望当使用者点击元素区域之外时,.shell-pop类的<div>元素被关闭。但是当前实现似乎不会触发任何操作,也没有任何日志或提示弹窗。我已经查看了相关文档,似乎一切都没问题? jQuery
$('document').ready(function () {
    updateCart();

    $(".shell").click(function (e) {
        e.preventDefault();
        $(".shell-pop").fadeIn(300, function () { $(this).focus(); });
    });

    $(".shell-pop").on('blur', function () {
        $(this).fadeOut(300);
        window.alert("work");
        console.log("works");
    });
});

HTML

<div class="options-area">
    <div class="options-popup shell-pop">
        <div class="swatches">
            <div class="colors-shell colors" id="green">
                <p class="prices-for-swatch">$14.23</p>
            </div>
            <div class="colors-shell colors" id="pink">
                <p class="prices-for-swatch">$7.23</p>
            </div>
            <div class="colors-shell colors" id="blue">
                <p class="prices-for-swatch">$11.25</p>
            </div>
            <div class="colors-shell colors" id="orange">
                <p class="prices-for-swatch">$10.23</p>
            </div>
            <div class="colors-shell colors" id="default-shell">
                <p class="prices-for-swatch">FREE</p>
            </div>
            <div class="colors-shell colors" id="exit">
                <img src="img/Silhouette-x.png" class="x-logo" alt="exit" />
                <p class="closeit">CLOSE</p>
            </div>
            <div class="shell square">
                <img src="img/controllers.png" class="item-icon" alt="controller-piece">
                <p class="name-of-item">Shell</p>
                <p id="shell_Price1" class="items-price">0.00</p>
            </div>        

1
什么是.shell-pop?如果元素不是输入元素,则模糊事件不会被触发。 - Rajaprabhu Aravindasamy
Shell-pop是一个包含多个div的div。我看到的许多示例都是使用div,所以我不确定为什么会导致它无法触发。 - Hot Java
blur() 在 div 上不起作用,我认为。请参见这里:https://dev59.com/jnM_5IYBdhLWcg3wt1k0#1259769 - Sam Fen
DOM Level 3规范指出,有效的目标包括WindowElement - 因此,div元素是blur事件的有效目标(在我刚刚在Firefox中运行的测试中它可以工作)。https://www.w3.org/TR/DOM-Level-3-Events/#event-type-blur - Fenton
2个回答

5
请为您的<div>添加tabindex属性。

tabindex是一个整数全局属性,用于指示元素是否可以接收输入焦点(即可聚焦),以及它是否应该参与顺序键盘导航,如果需要,其在什么位置。

请注意以下内容...
<div tabindex="-1"></div>

$('div').on('blur', function() {
    console.log('blurrr');
});

JSFiddle链接 - 简单演示


1
这将使元素能够接收焦点,这意味着模糊事件可能会触发。 tabindex为0还将使元素可通过键盘导航。 - Fenton
1
@Sohnee 这是真的!谢谢,我包含了一个链接,它解释了不同的值。 - scniro
啊,我明白了。我看到过那个,但是以为它只能用于在页面中进行字面上的制表符。我不应该做出这样的假设,应该对它进行更多的研究。 - Hot Java

1

模糊效果只会在表单元素上触发。您应该考虑其他方法。例如,您可以监听.shell-pop上的点击事件并确定其当前状态。

$(document).on('click', function(e){
    if ($(e.target).is('.shell-pop')) {
        alert('focused');
    } else {
        alert('blured');
    }
});

+1,这通常是在点击元素外部时关闭不可聚焦的元素的首选方式等。 - adeneo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接