我正在寻找一种方法来在用户点击contenteditable
div内部后捕获特定字符(或文本中的字符索引)。仅举一个例子,请考虑以下HTML:
<div contenteditable="true">
Hello world
</div>
假设用户点击&#34; o&#34;和&#34; r&#34;,有没有办法知道,使用JavaScript?
我想象Selection API会涵盖这一点,但到目前为止,我所有的询问都没有给我带来任何好处。
我感谢你能给我的任何帮助。
答案 0 :(得分:1)
You can see the caret position, i have done a small snippet for you here. Have a look at it.
enter code here
http://codepen.io/19sthil80/pen/pEooVR
答案 1 :(得分:1)
You can always do something like this. Codepen Link
I have put an alert in so that you can see that it does indeed know what you clicked and if you click a space as in between Hello and World it knows as well.
var div = document.getElementById("div");
function clickify (e) { var arr = (typeof e.innerText !== 'undefined') ? e.innerText.split("") : e.textContent.split(""), max = arr.length, i = 0, template = "$c", result = "";
for (; i < max; i += 1) {
result += template.replace("$c", arr[i]);
}
e.innerHTML = result;
}
clickify(div);