简体   繁体   中英

Prevent loss of element focus (Need cross-browser solution)

I'm using the following solution to prevent loss of focus of the #content textarea when the user has clicked on a .box element:

// Detect latest element clicked
$(document).mousedown(function(e) {
    lastElClicked = $(e.target);
});

// Prevent loss of focus for textarea when clicking on tools
$("#content").on("blur", function(event) {
    if (lastElClicked.attr('class') == 'box'){
        event.preventDefault();
        this.focus();
        return false;
    }
});

In a few words, on mouse down save the target element that has been clicked. On the blur of the #content textarea check if that last element clicked was a .box . If it was then prevent default, refocus the #content textarea and return false.

My solution works perfect under Chrome but I still loose focus under Safari and Firefox. How can I make this work cross browser?

EDIT:

The problem with the solutions offered is that the element actually looses focus and is refocused after. In Chrome with the code above I never actually loose fucus, which means selected text stays selected.

EDITED:

try this:

// Detect latest element clicked
$(document).mousedown(function(e) {
    window.lastElClicked = $(e.target);
});

// Prevent loss of focus for textarea when clicking on tools
$("#content").on("blur", function(event) {
    if (window.lastElClicked.attr('class') == 'box'){
        event.preventDefault();
        var that=this;
        setTimeout(function(){
            $(that).trigger('focus');
        },200);
        window.lastElClicked="";
        return false;
    }
});

Also this is a nice article on this bug which appears to be on Safari's part: http://bugs.jquery.com/ticket/7768

Alternatively you could try this one:

$('.box').click(function(event){
    event.preventDefault();
    $('input').each(function(){
        $(this).trigger('blur');
    });
    setTimeout(function(){
            $('#content').trigger('focus');
        },200);
});

finally I have to mention that it still loses the focus on the highlighted text which seems to me as an impossible task to achieve in this case!

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