无法“聚焦”可编辑的`div`元素

时间:2015-03-01 11:00:54

标签: javascript jquery html css firefox

我想将焦点设置为我的contentEditable div元素之一。但没有工作。

这是我的代码:



$(document).click(function () {
    $('div').focus();
});

div{
    border:1px solid red;   
}

<div contentEditable >&nbsp;</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

这是一个不使用jQuery的工作代码段(你没有在你的代码片段中加载)。我还添加了一个ID来获取正确的div

document.getElementById('edit-me').focus();
div { border:1px solid red; }
<div id="edit-me" contentEditable>&nbsp;</div>

答案 1 :(得分:1)

在执行jQuery之前,您应该等到整个文档加载完毕。

&#13;
&#13;
$(document).ready(function () {
    $('div').click(function () {
        $('div').focus();
    })
});
&#13;
div{
    border:1px solid red;   
}
&#13;
<div contentEditable >&nbsp;</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

导入jquery!耶!

$(document).ready(function () {
    //I replaced "click" with "ready" because think that you want to focus once loaded, not once you click somewhere in the document.
    //"click" can still be used if you want to focus once you clicked somewhere in your window
    $('div').focus();
});
div{
    border:1px solid red;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable >&nbsp;</div>