简体   繁体   中英

Why does the JQuery “blur” event listener not work as expected?

I have a mobile nav - I'm trying to write something that will take you straight to the "close" button, so that the user can close the mobile nav. I'm trying to trigger this when the last item in the menu loses focus. (when using your keyboard to tab through the menu)

However, what is happening right now - as soon as that last item receives focus, it jumps straight to the close button. So you don't even get a chance to click the link.

I'd expect "blur" to occur when you LEAVE the element, not focus on it...

Why is this happening?

$('.closeNav + ul a[href="#lastLink"]').blur(function() {
    $('.closeNav').focus();
});


<nav class="mobile fullScreen active" tabindex="0">
    <div class="in">
        <div class="closeNav" tabindex="0" aria-label="Close Navigation selectable">
            <img src="#">
        </div>
        <ul>
            <li class="first"><a href="#" class="">link</a>
                <ul>
                    <li class="first"><a href="#">link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li><a href="#" >link</a></li>
                    <li class="last"><a href="#" >link</a></li>
                </ul>
            </li>


            <li><a href="#">link</a>
                <ul>
                    <li class="first"><a href="#">link</a></li>
                </ul>
            </li>
            <li><a href="#" >link</a></li>
            <li class="last"><a href="#" class="">link</a>
                <ul>
                    <li class="first"><a href="#lastLink">Last link</a></li>
                </ul>
            </li>


        </ul>
    </div>
</nav>

To accomplish this you need to use the Next Siblings selector $("prev ~ siblings") Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector.

$('.closeNav ~ ul a[href="#lastLink"]').blur(function() {
    $('.closeNav').focus();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM