如何在偏移量的javascript中找到xy位置 [英] how to find xy position in javascript with offset

查看:148
本文介绍了如何在偏移量的javascript中找到xy位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我的javascript代码有问题..

hello i have some problem with my javascript code..

我想在javascript中获取所选文本的xy位置,我使用这样的越位函数:

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;
  }

但当我调用此函数时,位置X,Y的结果始终为0查找位置选定文本

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);

我使用的是mozilla firefox ..
请帮帮我

and i use mozilla firefox.. please help me

推荐答案

您需要在选择的一端插入一个虚拟元素。这是一个函数,用于获取所有主流浏览器(包括IE 6)中选择的开始或结束的坐标。请注意,这需要支持元素的 getBoundingClientRect()方法排除Firefox 2。如果你需要支持该浏览器,你可以在虚拟元素上使用类似 findPosX / Y 的函数而不是 getBoundingClientRect()

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);

这篇关于如何在偏移量的javascript中找到xy位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆