简体   繁体   中英

Make element unable to take focus

Bottom line: I'd like to disable (with jQuery) certain elements from being able to take focus, as opposed to removing focus that's already applied. My issue may be IE-8 specific, so I'll consider IE-8 focussed solutions.

For example, I have a months-nav for which sometimes some months may not be valid selections, but I want to still present the month. Rather than cluttering my server-side logic and complicating my markup by switching to a span instead of a link for the invalid month, I'm just adding an "invalid" class to the li (link container)

<li class="valid">
    <a href="/subpubs/yearMonth/2011-1">Jan</a>
</li>       

<li class="invalid">
    <a href="/subpubs/yearMonth/2011-2">Feb</a>
</li>

[etc.]

This jQuery works to turn off the link and remove focus:

$('.invalid  > a').click(function () { $(this).blur(); return false; });

But in IE8 (though not IE7, don't know about IE9), the removal of focus by .blur() has enough of a delay that there's a visible blink (even with lonesomeday's solution). So I'd like another approach, or perhaps just a fix for IE8.

Is there away to just disable the link from being able to take focus at all?

I once had the same problem, the best solution I found was to set the "tabindex" attr of the element to "-1". For example:

$('.invalid > a').attr('tabindex','-1');

The delay is probably in the construction of the jQuery object. You could do this quicker if you call the native blur method:

$('.invalid  > a').click(function () { this.blur(); return false; });

Though I think you should probably do this with focus instead, so that users can't tab their way to your elements:

$('.invalid  > a').focus(function () { this.blur(); return false; });

The other option would be to replace all your "invalid" links with span elements using jQuery:

$('.invalid > a').replaceWith(function() {
    return $('<span/>', {
        html: this.innerHTML,
        'class': 'disabled-link'
    });
});

You could consider switching all the invalid links to span markup using jQuery; this would be client-side rather than server-side. Is there a particular reason for removing the focus from these links? If they don't actually link to anything useful surely this is a case where server-side you should be replacing the links with just text?

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