我想知道如何将光标设置在可编辑元素的子元素中。我有一个内容可编辑的DIV,里面有SPAN,我想在单击DIV时将光标设置在SPAN中,以防止有人在DIV中输入。
<div class="custom-input" spellcheck="true" contenteditable="true">
"NOT HERE"
<span data-type="text">
"TYPE HERE"
<br>
</span>
</div>
我试过在jQuery中使用.focus()来做这件事,它可以工作,但只是突出显示SPAN并且光标保留在DIV中。
我正在尝试像Facebook聊天那样做。 Facebook聊天使用contenteditable元素进行聊天输入,如果您点击聊天框中的任意位置,光标始终会聚焦在用于输入的SPAN标签中。
答案 0 :(得分:0)
我最近必须这样做,以下是我最终的结果。
注意: 由于沙盒和诸如此类的原因,这似乎不适用于此处或jsFiddle。在本地主机或托管服务器上运行代码,您将看到它有效。
$(document).ready(function() {
var $element = $('.type-here');
createCaretPlacer($element, false); // set cursor and select text
createCaretPlacer($element, true, true); // set cursor at start
createCaretPlacer($element, true, false); // set cursor at end
});
function createCaretPlacer($element, collapse, atStart) {
var el = $element[0]; // get the dom node of the given element
el.focus(); // focus to the element
// feature test to see which methods to use for given browser
if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
// handle real browsers (not IE)
var range = document.createRange(); // create a new range object
range.selectNodeContents(el); // add the contents of the given element to the range
if(collapse) range.collapse(atStart); // collapse the rage to either the first or last index based on "atStart" param
var sel = window.getSelection(); // Returns a Selection object representing the range of text selected by the user or the current position of the caret.
sel.removeAllRanges(); // removes all ranges from the selection, leaving the anchorNode and focusNode properties equal to null and leaving nothing selected.
sel.addRange(range); // add the range we created to the selection effectively setting the cursor position
}
else if (typeof document.body.createTextRange != "undefined") {
// handle IE
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
if(collapse) textRange.collapse(atStart);
textRange.select();
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-input" spellcheck="true" contenteditable="true">
"NOT HERE"
<span data-type="text" class="type-here">
"TYPE HERE"
<br>
</span>
</div>
&#13;