我试图在单击按钮时检测光标的当前位置。但是我的脚本只能根据文本检测光标的位置,而不是计算html元素。如何使此功能也检测和计算html元素?示例如下。
HTML
<div>This is a text</div> <!-- If cursor is at after the word 'is',
position should be 7 -->
<div><ul><li>This is text with ul and li elements</li></ul></div>
<!-- If cursor is at after the word 'is',
position should be 15 (counting the ul and li elements) -->
<button class='button'>Button</button>
JS
$(document).ready(function() {
$('.button').click(function() {
var position = window.getSelection().getRangeAt(0).startOffset;
alert(position);
});
});
的jsfiddle
答案 0 :(得分:1)
也许像this:
HTML:
<div class="container">This is a text</div>
<div class="container"><ul><li>There is ul and li elements here</li></ul></div>
<button class='button'>Button</button>
JavaScript的:
$(document).ready(function() {
$('.button').click(function() {
var text = window.getSelection().anchorNode
if(text) {
var container = $(text).closest(".container");
var htmlLength = container.html().indexOf(text.textContent);
var position = window.getSelection().getRangeAt(0).startOffset;
alert(htmlLength + position);
}
});
});
答案 1 :(得分:0)
这应该有效:
$(document).ready(function() {
$('.button').click(function() {
var position = window.getSelection().getRangeAt(0).startOffset;
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var container = $(selection.getRangeAt(0).startContainer.parentNode).closest('div');
var text = container.text();
var htmlText = container.html();
position += htmlText.indexOf(text);
}
alert(position);
});
});