2010-03-04 16 views
9

텍스트 상자 요소 인 HTML <input>에서 선택한 텍스트의 문자 위치를 얻으려면 어떻게해야합니까? window.getSelection()은 텍스트 상자에서 작동하지 않습니다. jCaret텍스트 상자에서 선택한 텍스트 가져 오기

// Get start pos in intput box with id="box1" 
$("#box1").caret().start 

// Get end pos 
$("#box1").caret().end 

// Get selected text 
$("#box1").caret().text 
+0

@Ant - 자세한 정보가 필요합니다. 어떤 언어를 사용하고 있습니까? 이것은 브라우저에서만 (클라이언트 측) 또는 서버에서? – Oded

+0

은 javascript와 firefox라고 말합니다. window.getSelection()은 텍스트 상자에서 작동하지 않습니다. – alfred

답변

12

당신이 jQuery를 사용하는 경우, JQuery와 캐럿 플러그인을 살펴 Internet Explorer의 이전 버전을 지원할 필요가없는 경우 요소의 selectionEndselectionStart 속성 만 사용하면됩니다.

4

........

<script language=javascript> 
function getSelText() 
{ 
    var txt = ''; 
    if (window.getSelection) 
    { 
     txt = window.getSelection(); 
      } 
    else if (document.getSelection) 
    { 
     txt = document.getSelection(); 
      } 
    else if (document.selection) 
    { 
     txt = document.selection.createRange().text; 
      } 
    else return; 
document.aform.selectedtext.value = txt; 
} 
</script> 

<input type="button" value="Get selection" onmousedown="getSelText()"> 

<form name=aform > 
<textarea name="selectedtext" rows="5" cols="20"></textarea> 
</form> 

참조 : http://www.codetoad.com/javascript_get_selected_text.asp

관련 문제