2011-01-28 4 views
2

컨테이너 (DIV) 안에 여러 개의 HTML을 가져 와서 사용자가 일부를 선택하게하고 싶습니다. 내가 찾고있는 "편집 가능 영역"이 아닙니다. 사용자가 텍스트를 덮어 쓰거나 변경할 수 없도록하려는 경우. 그냥 표시하십시오.텍스트를 선택한 다음 AJAX 용 jQuery로 세 부분으로 나눕니다.

사용자가 선택한 후에는 무엇이 선택되었지만 선택한 부분이 어디 인지도 알고 싶습니다.

예 :

  1. 우리는 글 머리 기호 목록을 가지고 있고 사용자는 우리는 몇 가지 : 제목과 세 단락을 bulletline 3과 4

  2. 을 선택합니다. 그런 다음 사용자는 중간 단락의 일부를 선택합니다. 그 단락의 어디에 있는지 알고 싶습니다.

약간의 연구를 해본 결과, MSIE는 선택 항목의 startPos 및 endPos와 관련하여 선택에 문제가 있다고 생각합니다.

둘째, 표시된 텍스트가 전체 컨테이너 내부에 여러 번 있다면 어떻게해야합니까?

<div id="markable"> 

    <h1>Here is a nice headline</h1> 

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non 
     tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus 
     neque, tempus iaculis sapien consectetur id.</p> 

    <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus. 
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia 
    Curae; Quisque fringilla massa id libero commodo venenatis.</p> 

    <ol> 
    <li>here is a bullet line #1</li> 
    <li>here is a bullet line #2</li> 
    <li>here is a bullet line #3</li> 
    <li>here is a bullet line #4</li> 
    <li>here is a bullet line #5</li> 
    <li>here is a bullet line #6</li> 
    </ol> 

    <h2>here is a sub-headline</h2> 

    <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus. 
    Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent 
    per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et 
    malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
    consequat.</p> 

</div> 

문제는 사용자가 "템퍼"라는 단어를 충분히 알고 그것의 좋은하지, 나는 또한 단어의 어느 (어떤 단락을 알 필요를 선택하면 여기에 있습니다 : 여기

은 예입니다/headline/bullet 요소)입니다.

이유는 "독자"가 관심 분야/관심 분야를 발견 할 수 있기를 바랍니다. 때로는 전체 단락, 때로는 단 하나의 단어 또는 제목. 우리는 어떻게 든 선택되어 DOM에있는 "요소"에 (I 추측 위로부터 계산)를 감지 할 수 있다면

완벽한 솔루션

이 될 것입니다. 둘째, 특정 요소 내부에서 시작 지점과 끝 지점의 양. 내가 않는 일부 온라인 코드 편집기를 발견했습니다

우리가 다시 표시하고 무엇 이제까지 된 내용 백엔드를 알려줍니다 우리의 ASP.NET에 아약스의 일종을 할 수 있기 때문에 ... 위의 BUNCH + 필요한 것보다 훨씬 많지만이 솔루션은 솔루션이 훨씬 간단하다는 것을 믿습니다. jQuery 솔루션을 시작하기에 적절한 방법을 찾지 못한다.

jQuery Yoda가이를 읽고 있기를 바랍니다. :-)

답변

1
+0

쿨, 나는 당신에게서 더 많은 답변을 기대하지 않았다. 나는 그것을 검토하고 우리의 문제를 해결한다면 누가 "고맙다"고 말했는지 기억할 것입니다. 지금까지 고마워. – BerggreenDK

+0

굉장해! 이것은 그것을한다! – BerggreenDK

2

죄송합니다 이것은 일부 답변 일 뿐이며 모든 브라우저에서 선택이 시작되고 끝나는 요소의 색인을 제공하지만 선택 시작과 끝의 오프셋은 Gecko 및 WebKit 브라우저에서만 작동합니다 . IE는 내게 약간의 수수께끼 인 TextRange 객체 만 지원합니다 (이 답변의 맨 아래에있는 링크는 모든 브라우저를 포함하는 구현 예입니다)

이 솔루션은 색인을 반환합니다. 선택 영역에 #markable 컨테이너와 관련하여 포함 된 요소와 시작 및 끝 선택 색인 (포함 노드와 관련하여)

이 예제에서는 선택 항목을 포함하는 요소를 캡처하기 위해 이벤트를 사용하고 있지만 (브라우저 차이점을 나타냄) 이벤트 (Firefox, Opera, Chrome 및 Safari의 경우)를 Range 개체로 쉽게 수행 할 수 있습니다 당신에게주는 선택 시작하고 여기 (여기 http://www.quirksmode.org/dom/range_intro.html 추가 정보)

<html> 
<head> 

    <script src="http://code.jquery.com/jquery-1.4.4.js"></script> 
    <script> 

    var end; 
    var start; 

    indexes = new Array(); 
var endIndex; 
    var startIndex; 
    $(document).ready(function(){ 


$("#markable").mouseup(function(event){ 
end = event.target; 

indexes.push($("*", "#markable").index($(end))); 
//normalize start and end just in case someone selects 'backwards' 
indexes.sort(sortASC); 




event.stopPropagation() 
}) 

$("#markable").mousedown(function(event){ 
indexes.length=0; 
start = event.target; 
event.stopPropagation() 
indexes.push($("*", "#markable").index($(start))); 
}) 

$(".button").click(function(){ 

sel = getSel(); 

alert("Index of the element selection starts in (relative to #markable): "+indexes[0] +"\n" + 
"Index of the of the beginning of selection in the start node: "+ sel.anchorOffset+"\n" + 
"Index of the element selection ends in (relative to #markable): "+ indexes[1]+"\n"+ 
"Index of the of the end of selection in the end node: "+ sel.focusOffset) 

}) 

    }) 




function sortASC(a, b){ return (a-b); } 
function sortDESC(a, b){ return (b-a); } 

function getSel() 
{ 
    var txt = ''; 
     if (window.getSelection) 
    { 
        txt = window.getSelection(); 
             } 
    else if (document.getSelection) 
    { 
        txt = document.getSelection(); 
            } 

    else if (document.selection) 
    { 
        txt = document.selection.createRange(); 
            } 
    else return; 
return txt; 
} 
</script> 

</head> 
<body> 
<div id="markable"> 

    <h1>Here is a nice headline</h1> 

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque non 
     tempor metus. Ut malesuada posuere nunc eu venenatis. Donec sagittis tempus 
     neque, tempus iaculis sapien consectetur id.</p> 

    <p>Nulla tempus porttitor pellentesque. Curabitur cursus dictum felis quis tempus. 
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia 
    Curae; Quisque fringilla massa id libero commodo venenatis.</p> 

    <ol> 
    <li>here is a bullet line #1</li> 
    <li>here is a bullet line #2</li> 
    <li>here is a bullet line #3</li> 
    <li>here is a bullet line #4</li> 
    <li>here is a bullet line #5</li> 
    <li>here is a bullet line #6</li> 
    </ol> 

    <h2>here is a sub-headline</h2> 

    <p>Aenean auctor fringilla dolor. Aenean pulvinar tortor sed lacus auctor cursus. 
    Sed sit amet imperdiet massa. Class aptent taciti sociosqu ad litora torquent 
    per conubia nostra, per inceptos himenaeos. Fusce lectus neque, rhoncus et 
    malesuada at, blandit at risus. Vivamus rhoncus ante vel erat mollis 
    consequat.</p> 

</div> 
<input type=button class=button value="Get selection data"> 


</body> 
</html> 

각각 종료하고있는 DOM 노드입니다 anchorNode 및 focusNode 당신에게 크로스 브라우저 솔루션을 더 줄 것이다 링크가있다 (아래로 스크롤 예 2) http://help.dottoro.com/ljjmnrqr.php

EDIT : IE의 경우 텍스트 범위를 가져 오기 위해 document.body.createTextRange()를 사용해야합니다. 나는 아직도 당신이 anchorOffset에 해당하는 얻을 방법을 잘 모르지만, 다음 링크는 도움이 될 수 있습니다 http://bytes.com/topic/javascript/answers/629503-ie-selection-range-set-range-start-click-position-get-char-offset

+0

멋진 당신이 원하는 모든 것을 할 것입니다 크로스 브라우저 라이브러리입니다! 나는 그것을 내일 볼 것이다. 지금까지 감사드립니다. – BerggreenDK

관련 문제