2010-11-30 17 views
2

일부 노드의 모든 문자의 위치 (왼쪽, 위)를 얻는 방법? 나는 단지 하나의 방법을 알고있다. 그것의 모든 문자를 자기 꼬리표로 감싼 다음 좌표를 얻을 수있다. 하지만 약간 느리다.모든 문자의 위치를 ​​얻는 방법

+0

설명 된 방법 외에는 선택의 여지가 많지 않을까 우려됩니다. 모든 문자의 위치를 ​​파악하려면 각 문자의 정확한 크기를 알아야하며 각 글꼴의 크기가 각 문자마다 다르기 때문에 거의 불가능한 작업입니다. –

+0

가능한 중복 : http://stackoverflow.com/questions/5143534/get -the-position-of-element-of-an 요소 –

답변

5

내 질문에 대한 답변을 찾았습니다. 범위 인터페이스는 필요한 모든 정보를 제공 할 수 있습니다 (추가 정보 - http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html).

+0

이며 여기에서 찾을 수 있습니다. https://stackoverflow.com/a/29903556/142317 –

1

이미 본 문자의 너비를 캐싱 할 수있다.

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

그러면 다음에이 기능을 호출 할 때 각 색인을 붙잡고 가까이에서 시작할 수도 있습니다. 즉, 각 캐릭터가 아닌 보통 ~ 50 자 (영숫자 + 구두점 등)의 시간을 제외하고 DOM을 벗어나야합니다.

이것은 모노 스페이스 폰트에서는 효과가 있지만, 다른 유형에서는 약간의 장점이 있다고 생각합니다. 여러 브라우저에 대한 랩핑 조사 만하면됩니다.

또한 여기서는 왼쪽 맞춤 등을 가정합니다. 실제 코드 솔루션보다 더 많은 아이디어입니다.

+0

좋은 생각, 글꼴 패밀리와 글꼴 크기 (아마도 jQuery로 찾을 수 있습니까?)를 고려하고 캐시 키에 추가해야합니다. 일반적인 키는 "G_Tahoma_14"이고 다른 하나는 "G_Tahoma_12"입니다. :) –

+1

Range 객체를 사용하여 내 문제를 해결하고 span 노드의 모든 심볼을 래핑하는 것보다 훨씬 빠름을 언급합니다. 이 작업을 수행하는 코드는 –

관련 문제