programing

커서/케어 위치를 설정하는 가장 좋은 방법은 무엇입니까?

fastcode 2023. 3. 6. 21:32
반응형

커서/케어 위치를 설정하는 가장 좋은 방법은 무엇입니까?

TinyMCE가 공동 작업한 텍스트 영역에 콘텐츠를 삽입할 경우 커서/캐럿 위치를 설정하는 가장 좋은 방법은 무엇입니까?

하고 tinyMCE.execCommand("mceInsertRawHTML", false, content);내용을 삽입하고, 커서의 위치를 컨텐츠의 마지막에 설정합니다.

다.document.selection ★★★★★★★★★★★★★★★★★」myField.selectionStartTinyMCE가 (그들의 포럼에서 찾을 수 없는 것을 통해) 지원할 것 같거나 정말 추악한 해킹이 될 것 같습니다.

나중에 : 좋아졌습니다.WordPress에 TinyMCE를 로드하면 내장된 iframe에 에디터 전체가 로드된다는 것을 알게 되었습니다.

이후 (2):사용할 수 있습니다.document.getElementById('content_ifr').contentDocument.getSelection();할 수 .getRangeAt(0)조금씩 나아지고 있습니다.

먼저 작성할 콘텐츠의 끝에 스팬을 추가해야 합니다.

var ed = tinyMCE.activeEditor;

//add an empty span with a unique id
var endId = tinymce.DOM.uniqueId();
ed.dom.add(ed.getBody(), 'span', {'id': endId}, '');

//select that span
var newNode = ed.dom.select('span#' + endId);
ed.selection.select(newNode[0]);

이는 TinyMCE 개발자가 Selection.js를 작성할 때 사용한 전략입니다.기본 소스를 읽는 것은 이런 종류의 문제에 큰 도움이 될 수 있습니다.

이 문제(전용)에 15시간 이상 소비한 후, FF와 Safari에서는 동작하지만 IE에서는 동작하지 않는 부분적인 솔루션을 발견했습니다.지금은 이 정도면 충분합니다만, 앞으로도 계속 작업해 나갈지도 모릅니다.

해결 방법:현재 캐럿 위치에 HTML을 삽입할 때 사용하는 가장 좋은 기능은 다음과 같습니다.

tinyMCE.activeEditor.selection.setContent(htmlcontent);

Firefox 및 Safari에서 이 함수는 WordPress가 TinyMCE 편집기로 사용하는 iframe 내의 현재 캐럿 위치에 콘텐츠를 삽입합니다.IE 7과 8의 문제는 이 함수가 iframe이 아닌 페이지 맨 위에 콘텐츠를 추가하는 것처럼 보인다는 것입니다(텍스트 에디터를 완전히 놓치는 경우).이 문제에 대처하기 위해서, IE 대신에 이 기능을 사용하는 이 코드에 근거하는 조건부 스테이트먼트를 추가했습니다.

tinyMCE.activeEditor.execCommand("mceInsertRawHTML", false, htmlcontent);

그러나 이 두 번째 함수의 문제는 캐럿 위치가 호출된 후 게시 영역의 선두로 설정된다는 것입니다(브라우저 범위에 따라 캐럿 위치를 호출할 가능성은 없습니다.이 함수는 삽입된 콘텐츠의 끝에 있는 캐럿 위치를 첫 번째 함수로 복원하기 위해 작동한다는 것을 알게 되었습니다.

tinyMCE.activeEditor.focus();

또한 삽입된 텍스트의 길이를 계산할 필요 없이 삽입된 콘텐츠의 끝까지 캐럿 위치를 복원합니다.단점은 첫 번째 삽입 기능에서만 작동하며 IE 7 및 IE 8에서 문제가 발생하는 것 같습니다(TinyMCE보다 WordPress 오류일 수 있음).

말이 많은 대답인 거 알아해명을 위해 자유롭게 질문해 주세요.

커서를 끝까지 이동시키는 것은 너무 간단해서 나는 이것을 하기 위해 다른 온라인에 게시된 끔찍한 글들을 믿을 수 없다.Spocke씨의 답변은 처음에는 도움이 되지 않았지만, 결국 API 문서를 통해 답을 얻을 수 있었습니다."모든 내용을 선택한 후 선택 항목 축소":

ed.selection.select(ed.getBody(), true); // ed is the editor instance

ed.selection.collapse(false);

이 스레드가 구글에서 가장 먼저 떠오른 것 중 하나이기 때문에 다른 사람에게 도움이 되었으면 합니다.

제가 찾은 가장 좋은 방법은 temp id로 콘텐츠를 삽입하고 advlink 플러그인에서 찾은 트릭을 사용하여 포커스를 주는 것입니다.

이게 도움이 됐으면 좋겠다.

var ed = tinyMCE.activeEditor;

ed.execCommand('mceInsertContent', false, '<a id="_mce_temp_rob" href="http://robubu.com">robubu.com</a>');

//horrible hack to put the cursor in the right spot
ed.focus(); //give the editor focus
ed.selection.select(ed.dom.select('#_mce_temp_rob')[0]); //select the inserted element
ed.selection.collapse(0); //collapses the selection to the end of the range, so the cursor is after the inserted element
ed.dom.setAttrib('_mce_temp_rob', 'id', ''); //remove the temp id

팝업을 통해 이 작업을 수행하는 경우 추가가 필요할 것 같습니다.

tinyMCEPopup.storeSelection();

를 클릭하여 팝업을 닫습니다.

Wordpress 커스텀메타박스의 콘텐츠를 TinyMCE 에디터에 삽입하려는 사용자는 이 솔루션을 사용할 수 있습니다.이 페이지의 다른 스크립트를 포함해 많은 스크립트를 시험해 보았습니다.위의 답변은 커스텀 TinyMCE 버튼을 설치할 때 도움이 되었지만 이 시나리오에서는 잘 되지 않았습니다.

올바른 해결책은 tinyMCE api tinymce.dom을 사용하는 것입니다.선택.

http://www.tinymce.com/wiki.php/API3:class.tinymce.dom.Selection

구문은 다음과 같습니다.

var rng = tinymce.DOM.createRng();  // the range obj
var newNode = editor.dom.select(...    // find the correct selector so that newNode is the element of your editor text
rng.setStart(newNode.firstChild, 0); // 0 is the offset : here it will be at the beginning of the line.
rng.setEnd(newNode.firstChild, 0);
editor.selection.setRng(rng);

효과가 있어요 제가 직접 쓰죠

자, 여기 우리 프로젝트의 해결책이 있습니다.는 변화를 주는 이었다.(+)/(-)/(?)사용자가 입력하는 동안 "온 더 플라이"로 적절한 이미지에 문자열을 입력합니다.

문제가 있었습니다.문자열을 이미지로 변경한 후 커서가 예상대로 끝이 아니라 이미지의 선두로 이동했습니다.

이미지 끝에 커서를 이동시키는 코드의 대부분을 추가했기 때문에 사용자는 "점프" 커서에 인터럽트 없이 연속적으로 입력할 수 있습니다.

: 사용법 사용방법editor.getBody임시 스팬을 작성하는 보다 우아한 방법이 있습니다.또, 필요한 조작 후에 즉시 삭제할 수도 있습니다.

if (value.match(/\([+?-]\)/)) {
        // set current cursor via span
        editor.selection.setContent('<span id="temp-span"/>');

        // refresh Content with new span
        value = editor.getContent();

        // changing (+)/(-)/(?) to the appropriate image "on the fly"
        value = value.replace('(+)', ' <img src="https://url_here/static/task_manager/img/add.png">&nbsp;');
        value = value.replace('(-)', ' <img src="https://url_here/static/task_manager/img/forbidden.png">&nbsp;');
        value = value.replace('(?)', ' <img src="https://url_here/static/task_manager/img/help_16.png">&nbsp;');
        if (this.state.editor) {
            editor.setContent(value);

            // move cursor to the latter span
            var newNode = editor.dom.select('span#temp-span');
            editor.selection.select(newNode[0]);
            editor.selection.setContent('');
        }
        // and refreshing content again w/o span
        value = editor.getContent();
    }

html 부모 요소에 머무르지 않고 현재 캐럿 위치에 html 콘텐츠를 다음과 같이 삽입합니다.

editor.insertContent( '<div>My html inserted code here...</div>' + '&nbsp;' , {format: 'html'} );

끝에 있는 빈칸은 추가 입력된 텍스트가 삽입된 div 요소 외부에 배치되도록 합니다.

현재 선택/관리 위치에 DOM 노드를 삽입합니다.

tinyMCE.activeEditor.selection.setNode(tinyMCE.activeEditor.dom.create('img', {src : 'some.gif', title : 'some title'}));

여기 내 돈 2센트만 넣었어이것들 중 어느 것도 내 질문에 대답하지 않았다.HTML 요소가 아니라 텍스트 블록을 넣었습니다.[code][/code]예를 들어, 커서가 둘 사이에 있어야 합니다.

@robyates answer의 일부를 사용하여 임시 HTML 요소를 두 개 사이에 넣었습니다.[code]태그를 지정하고 초점을 맞춘 후 HTML 요소를 완전히 제거합니다.코드는 다음과 같습니다.

setup : function(ed) {
    // Add a custom button
    ed.addButton('codeblock', {
        title : 'Code Block',
        text : '[code/]',
        icon: false,
        onclick : function() {
            // Add you own code to execute something on click
            ed.focus();
            //ed.selection.setContent('[code][/code]');
            ed.execCommand('mceInsertContent', false, '[code]<span id="_cursor" />[/code]');

            ed.selection.select(ed.dom.select('#_cursor')[0]); //select the inserted element
            ed.selection.collapse(0); //collapses the selection to the end of the range, so the cursor is after the inserted element
            ed.dom.remove('_cursor'); //remove the element
        }
    });
}

여기서부터 제가 표절했어요.

function setCaretTo(obj, pos) { 
    if(obj.createTextRange) { 
        /* Create a TextRange, set the internal pointer to
           a specified position and show the cursor at this
           position
        */ 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) { 
        /* Gecko is a little bit shorter on that. Simply
           focus the element and set the selection to a
           specified position
        */ 
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    } 
} 

다음과 같은 솔루션을 사용할 수 있습니다.

// params: 
//   $node: jquery node with tinymce loaded 
//   text: text to set at then before caret
function setTextAndCaretToEnd($node, text) {
     var ed = window.tinyMCE.get($node.attr("id"));
     ed.focus();
     ed.selection.setContent(text);
}

Tiny 버전 5에서는

editor.selection.setCursorLocation(editor.getBody(), editor.getBody().childElementCount);

언급URL : https://stackoverflow.com/questions/1253303/whats-the-best-way-to-set-cursor-caret-position

반응형