Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取每个字符的位置_Javascript_Dom - Fatal编程技术网

Javascript 如何获取每个字符的位置

Javascript 如何获取每个字符的位置,javascript,dom,Javascript,Dom,如何获取某个节点中每个字符的位置(左、上)?我只知道一种方法:将每个字符包装在它自己的标记中,然后我们就可以得到它的坐标。但是速度有点慢你可以缓存你已经看到的字符宽度 function findOffset(index) { // Set some variables early on var sizes = {}, text = "The text you are getting an offset from.", line

如何获取某个节点中每个字符的位置(左、上)?我只知道一种方法:将每个字符包装在它自己的标记中,然后我们就可以得到它的坐标。但是速度有点慢

你可以缓存你已经看到的字符宽度

function findOffset(index) {
  // Set some variables early on
  var sizes          = {},
      text           = "The text you are getting an offset from.",
      lineHeight     = 16,  // You can get this dynamically if you want
      containerWidth = 500, // Same with this one
      leftOffset     = 0,
      topOffset      = 0,
      i              = 0,
      cur;

  // Loop through and count up the sizes of each character until this one
  for (; (i < text.length) && (i <= index); i++) {

    // Set the current character
    cur = text.charAt(i);

    // Check to see if we have a size
    if ( typeof size[cur] == "undefined" ) {
      // If not: Wrap it in a span (You seemed to already know how to do this)
      // then cache the result
      size[cur] = findWidthByTemporarilyWrappingInASpan(text, i);
    }

    // If it's greater than a line can hold, we'll wrap
    if ( (sizes[cur] + leftOffset) > containerWidth ) {

      // Reset the left offset
      leftOffset = 0;

      // Increment the top offset
      topOffset += lineHeight;
    }
    // Otherwise, increment from the left
    else {
      leftOffset += sizes[cur];
    }
  }

  // return an object with the coordinates
  return {
    leftOffset: leftOffset,
    topOffset : topOffset
  };
}
函数findOffset(索引){
//在早期设置一些变量
变量大小={},
text=“从中获取偏移量的文本。”,
lineHeight=16,//如果需要,您可以动态地获取它
containerWidth=500,//与此相同
leftOffset=0,
topOffset=0,
i=0,
cur;
//循环并计算每个字符的大小,直到这个字符
对于(;(i
然后,你甚至可以记住你抓取的每个索引,并在下次调用这个函数时从一个接近的索引开始。这意味着你远离dom,除了通常不超过50次(字母数字+标点符号等),而不是每个字符

这当然适用于等距字体,但我认为它对其他类型的字体也有一些好处。你只需要对不同的浏览器进行包装研究


另外,请注意,这假设了左对齐等。这与其说是一个实际的代码解决方案,不如说是一个想法。

我在我的问题范围界面上找到了答案,可以提供我需要的所有信息(更多信息-).

我担心除了您描述的方法之外,您没有太多选择。要知道每个字符的位置,您必须知道每个字母的确切大小,这几乎是不可能的任务,因为每个字符的字体大小不同。可能的重复:好主意,需要考虑字体系列和字体大小(可能可以在jQuery中找到?)并将其添加到缓存密钥中,例如,典型的密钥将是“g_Tahoma_14”和另一个“g_Tahoma_12”。)正如我提到的,使用范围对象解决了我的问题,比在span节点中包装每个符号快得多。执行此操作的代码可以在此处找到: