How to find xy position in javascript with offset

Hi, I have some problems with my javascript code.

I want xy to position the selected text in javascript, and I use the offside function as follows:

function findPosX(obj) { var curleft = 0; if(obj.offsetParent) while(1) { curleft += obj.offsetLeft; if(!obj.offsetParent) break; obj = obj.offsetParent; } else if(obj.x) curleft += obj.x; return curleft; } function findPosY(obj) { var curtop = 0; if(obj.offsetParent) while(1) { curtop += obj.offsetTop; if(!obj.offsetParent) break; obj = obj.offsetParent; } else if(obj.y) curtop += obj.y; return curtop; } 

but the result of X, Y position is always 0 when I call this function to find the selected text position

 var select = window.getSelection(); var posX = findPosX(select); var posY = findPosY(select); 

and i am using mozilla firefox .. please help me

+2
source share
1 answer

You will need to insert a dummy element at one end of the selection. Here is the function to get the coordinates of the beginning or end of the selection in all major browsers, including IE 6. Note that this requires support for the getBoundingClientRect() method of elements, which excludes Firefox 2. If you need to support this browser, you can use something like your findPosX/Y functions on a dummy element instead of getBoundingClientRect() .

 function getSelectionCoordinates(start) { var x = 0, y = 0, range; if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(sel.rangeCount - 1); range.collapse(start); var dummy = document.createElement("span"); range.insertNode(dummy); var rect = dummy.getBoundingClientRect(); x = rect.left; y = rect.top; dummy.parentNode.removeChild(dummy); } } else if (document.selection && document.selection.type != "Control") { range = document.selection.createRange(); range.collapse(start); x = range.boundingLeft; y = range.boundingTop; } return {x: x, y: y}; } var coords = getSelectionCoordinates(true); alert(coords.x + ", " + coords.y); 
+2
source

All Articles