2012-11-07 2 views
3

커서를 텍스트 영역에 놓은 다음 동일한 페이지에서 트리 뷰 노드를 클릭하여 텍스트 영역에 노드의 텍스트를 선택해야하는 시나리오가 있습니다. 트리 노드를 클릭하기 직전에 커서를 놓습니다.IE와 관련된 문제 커서 위치의 텍스트 영역에 텍스트 삽입

나는

Inserting text in textarea at cursor position if cursor placed else text should append at last in IE

Insert text into textarea with jQuery

How to insert text at the current caret position in a textarea

Inserting text at cursor in a textarea, with Javascript

Inserting text after cursor position in text areа

, 아래를 포함하여 스택 오버 플로우에 많은 답변을 얻었다

How do I insert some text where the cursor is?

FF와 Chrome은 위의 솔루션과 잘 작동하지만 IE 8 이하 버전은 포커스가 다른 컨트롤로 이동하면 IE9에서 확인하지 못했습니다. 우리는 또한 if ('selection' in document)

대신 if(el.selectionStart || el.selectionStart == '0') 대신 if ('selectionStart' in el)if(document.selection)을 사용할 수 있지만 초점이 때이 오류가 발생합니다 :

(function ($) { 
    $.fn.getCursorPosition = function() { 
     var el = $(this).get(0); 
     var pos = 0; 
     if ('selectionStart' in el) { 
      pos = el.selectionStart; 
     } else if ('selection' in document) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength 
     } 
     return pos; 
    } 
})(jQuery); 

참고 :

이 아래 또는 IE 비슷한 구현 거의 모든 글입니다 먼저 다른 컨트롤로 이동 한 다음 실행합니다. 내 경우에는 사용자가 노드를 통과 할 때 포커스가 트리 노드로 이동합니다.

이 시나리오에 대한 해결책이 있습니까?

텍스트 영역에 onkeyup 및 onclick을 작성하고 커서 위치를 숨겨진 필드에 저장하려고합니다. 그래서 포커스가 다른 컨트롤로 이동하면 숨겨진 필드가 텍스트 영역의 커서 위치를 가져옵니다. 그 동안 나중에 여기에 게시 할 예정입니다. 누군가 좋은 아이디어가 있다면 공유하십시오. 내가 코드, 그것뿐만 아니라 IE에서 작업 를 만들기 위해 아래가 위에서 언급 한 바와 같이

미리

답변

2

에 감사드립니다 (또한 단지에 onblur 대신이이 사건의 문제에 대해 생각하지만 초점이 작동하지 않았다 이미 숨겨진 변수를 설정하기 위해 코드가 실행될 때 손실 됨)

아래 구현 내 경우에는 정상적으로 작동합니다.

if ($("#myTextArea").get(0).selectionStart == undefined) { 
    $("#myTextArea").click(function (e) { 
     $("#hdnTextAreaPosition").val($("#myTextArea").getCursorPosition()); 
    }); 
    $("#myTextArea").keyup(function (e) { 
     $("#hdnTextAreaPosition").val($("#myTextArea").getCursorPosition()); 
    }); 
} 
이벤트 위

(의 keyup 클릭)이 글로벌 스크립트에 있고 selectStart의 경우에만 첨부됩니다 것은

function getTextAreaCursorPosition() { 
    if ($("#myTextArea").get(0).selectionStart == undefined) { 
     return $("#hdnTextAreaPosition").val(); 
    } 
    else { 
     return $("#myTextArea").getCursorPosition(); 
    } 
} 


function insertToMyTextArea(textToInsert) { 
    $("#myTextArea").focus(); 
    var cursorPosition = getTextAreaCursorPosition(); 
    var myContent = $("#myTextArea").val(); 
    $("#myTextArea").val(myContent.substring(0, cursorPosition) + textToInsert + myContent.substring(cursorPosition)); 
} 

insertToMyTextArea이 주요 기능의 난입니다 정의되지 트리 노드를 클릭 할 때 호출됩니다.

이벤트 대신 다른 대안을 사용할 수 있다면 의견을 공유하십시오.

+0

나는'CSTE 연구진 ('대한 focusOut', ...)'(또는 .focusout()를 사용, 동일 :

나는 이전의 대답이 정확한 경우를 다루었 포커스를 잃기 전에 호출되는 선택 위치를 저장합니다. 또한 이벤트 거품이 생기므로 부모 요소에서도이를 잡을 수 있습니다 (흐림 효과는 거품이 나지 않음). – Silentdrummer

관련 문제