在IE> = 9和非IE浏览器(Firefox4+,自2009年初发布的WebKit浏览器,Opera11,也许更早)中,可以使用的
getClientRects()方法
Range。在IE4-10中,您可以使用的
boundingLeft和
boundingTop属性,这些属性
TextRange可以从选择中提取。这是一个功能,可以在最新的浏览器中完成您想做的事情。
请注意,在某些情况下,您可能会错误地获取坐标
0,0,如@Louis的注释中所述。在这种情况下,您将不得不采用临时插入元素并获得其位置的解决方法。
码:
function getSelectionCoords(win) { win = win || window; var doc = win.document; var sel = doc.selection, range, rects, rect; var x = 0, y = 0; if (sel) { if (sel.type != "Control") { range = sel.createRange(); range.collapse(true); x = range.boundingLeft; y = range.boundingTop; } } else if (win.getSelection) { sel = win.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0).cloneRange(); if (range.getClientRects) { range.collapse(true); rects = range.getClientRects(); if (rects.length > 0) { rect = rects[0]; } x = rect.left; y = rect.top; } // Fall back to inserting a temporary element if (x == 0 && y == 0) { var span = doc.createElement("span"); if (span.getClientRects) { // Ensure span has dimensions and position by // adding a zero-width space character span.appendChild( doc.createTextNode("u200b") ); range.insertNode(span); rect = span.getClientRects()[0]; x = rect.left; y = rect.top; var spanParent = span.parentNode; spanParent.removeChild(span); // Glue any broken text nodes back together spanParent.normalize(); } } } } return { x: x, y: y };}


