防止元素焦点丢失(需要跨浏览器解决方案)

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

本文关键字:浏览器 解决方案 元素 焦点      更新时间:2023-09-26

当用户点击.box元素时,我使用以下解决方案来防止#content文本区域的焦点丢失:

// 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;
    }
});

简而言之,按下鼠标保存已单击的目标元素。在#content文本区域的模糊检查,如果最后一个元素点击是.box。如果它是防止默认的,重新聚焦#content文本区域并返回false。

我的解决方案在Chrome下工作完美,但我仍然在Safari和Firefox下失去焦点。我怎样才能使这个工作跨浏览器?

编辑:

提供的解决方案的问题是元素实际上失去了焦点,然后重新聚焦。在Chrome与上面的代码,我从来没有真正松散的fucus,这意味着选择的文本保持选中。

edit:

试试这个:

// 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;
    }
});

这也是一篇很好的关于这个错误的文章,似乎是Safari的一部分:http://bugs.jquery.com/ticket/7768

或者你可以试试这个:

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

最后我不得不提的是,它仍然失去了对高亮文本的关注,在我看来,在这种情况下,这是一项不可能完成的任务!