簡體   English   中英

如何在contentEditable元素的子元素中設置光標?

[英]How to set the cursor in the child of a contentEditable element?

我想知道如何在可編輯元素的子元素中設置光標。 我有一個內容可編輯的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聊天使用可編輯內容的元素作為聊天輸入,如果您在聊天框中單擊任意位置,光標將始終聚焦在用於輸入的SPAN標簽上。

我最近不得不這樣做,下面是我最終得到的結果。

注意: 由於沙箱和其他功能,在這里或在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(); } } 
 <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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM