问题
hello i have some problem with my javascript code..
i want to get xy position the selected text in javascript, and i use offside function like this :
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 position X,Y always 0 when i call this function to find position selected text
var select = window.getSelection();
var posX = findPosX(select);
var posY = findPosY(select);
and i use mozilla firefox.. please help me
回答1:
You will need to insert a dummy element at one end of the selection. Here's a function to get the coordinates of the start or end of the selection in all major browsers, including IE 6. Note that this requires support for the getBoundingClientRect()
method of elements, which rules out Firefox 2. If you need to support that browser, you can use something like your findPosX/Y
functions on the 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);
来源:https://stackoverflow.com/questions/4122315/how-to-find-xy-position-in-javascript-with-offset