我正在使用Javascript構建一個簡單易用的文本編輯器,基本上是一個所見即所得的編輯器。我將使用contenteditable
屬性作爲主包裝(.wrapper
)。當您在.wrapper
內按下輸入時,會將帶有唯一id
的新<p>
元素附加到包裝。Javascript - 在[contenteditable]的子元素中獲取插入符號元素
我需要一種方法來獲取當前選擇的.wrapper
的哪個子元素(即正在聚焦或在其中有插入/文本標記)。
我搜索了幾天沒有任何結果,我試過使用document.elementFromPoint()
但沒有任何正確的結果。
當使用$(":focus")
時,我得到整個.wrapper
而不是特定的子元素。
編輯:
例HTML結構:
<div class="container t-wrapper" contenteditable>
</div>
實施例的Javascript代碼:
$(document).ready(function() {
$currentElement = $("[contenteditable]");
$(".t-wrapper").each(function() {
var id = generateIdentifier(6); // Ignore this
/* This creates the initial <p> child element, where you start typing. */
$(this).html('<p class="t-empty t-first" id="' + id + '"></p>');
$(this).on("mouseup", function() {
/* $currentElement = whatever element the caret is inside. */
});
$(this).on("keyup", function() {
/* $currentElement = whatever element the caret is inside. */
});
));
});
編輯2:
我設法GE它與mouseup
事件相當合作,因爲你實際上點擊了一些東西。但是,在使用鍵盤移動插入符號時,我需要此功能。或者,我需要一些方法來獲取插入符號的位置,然後使用document.elementFromPoint()
來獲取特定元素。
您是否嘗試過只對選定的節點上使用CONTENTEDITABLE?例如,您可以將新的'p'設置爲'contenteditable =「true」',同時禁用所有其他元素。在瀏覽節點樹時(單擊或箭頭鍵),可以將'contenteditable'屬性移到下一個元素。這似乎至少可以使用':focus'搜索子節點。 –
有一段代碼嗎? –
@ freestock.tk添加了一些基本的示例代碼。 –