通过Javascript计算HTML中的开始和结束选择索引. [英] Calculating start and end selection indices in HTML through Javascript.
本文介绍了通过Javascript计算HTML中的开始和结束选择索引.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
如何在contentEditable的"div"中的IE之外的浏览器中获取开始和结束选择索引.例如,IE具有以下方法.
Hi All,
How can I get the start and end selection indices in browsers other than IE in contentEditable ''div''. For Ex., IE has the following method.
var oSelection;
var oTxtRange;
var units = -100000;
var iStartIndex = -1, iEndIndex = -1;
if(document.selection) // IE..
{
oSelection = document.selection;
oTxtRange = oSelection.createRange();
if(oTxtRange)
{
iStartIndex = oTxtRange.moveStart('character',units);
iEndIndex = oTxtRange.moveEnd('character',units);
iStartIndex *= -1;
iEndIndex *= -1;
}
}
我了解上述方法不是W3C标准.我已经遍历了有关Selection和Range对象的W3C文档,但仍然不禁为Chrome和FireFox找到解决方案.
在此先感谢:-)
I understand that above method is not a W3C standard. I have gone through W3C documentation for Selection and Range object, but still couldn''t help finding solution for Chrome and FireFox.
Thanks in Advance :-)
推荐答案
大家好,
最后,我找到了适用于非IE浏览器的以下解决方案.
Hi All,
Finally I found the following solution for Non-IE browsers.
function getBodyTextOffset(node, offset) {
var sel = window.getSelection();
var range = document.createRange();
range.selectNodeContents(document.body);
range.setEnd(node, offset);
sel.removeAllRanges();
sel.addRange(range);
return sel.toString().length;
}
function getSelectionOffsets() {
var sel, range;
var start = 0, end = 0;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(sel.rangeCount - 1);
start = getBodyTextOffset(range.startContainer, range.startOffset);
end = getBodyTextOffset(range.endContainer, range.endOffset);
sel.removeAllRanges();
sel.addRange(range);
alert(start + ", " + end);
}
else if (document.selection) {
// IE stuff here
}
}
return {
start: start,
end: end
};
}
这篇关于通过Javascript计算HTML中的开始和结束选择索引.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文