简体   繁体   English

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

[英]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: 我使用以下解决方案来防止用户单击.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;
    }
});

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 . #content文本区域的模糊情况下,检查最后单击的元素是否为.box If it was then prevent default, refocus the #content textarea and return false. 如果那是防止默认设置的原因,请重新调整#content文本区域的#content并返回false。

My solution works perfect under Chrome but I still loose focus under Safari and Firefox. 我的解决方案在Chrome上运行完美,但在Safari和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. 在带有上述代码的Chrome浏览器中,我从未真正放松过焦点,这意味着所选文本保持选中状态。

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 另外,这是一篇有关该错误的不错的文章,似乎出现在Safari的一部分: 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! 最后,我不得不提的是,它仍然失去了对突出显示文本的关注,在我看来,这在这种情况下是无法完成的任务!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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