2013-06-25 2 views
2

다른 내용 편집 가능 div의 내용 안에 div를 어떻게 삽입합니까? 부모 div는 내용을 편집 할 수있는 div이며 문자열 내용을 포함합니다. 커서 위치에 '@'를 입력 할 때 다른 내용 편집 가능한 div를 삽입하고 싶습니다. 예를 들어 다른 div의 내용에 div를 삽입하는 방법은 무엇입니까?

,
<div id="target" class="text-area" contenteditable='true'>This text can be anything... how to insert a div when i type start typing @... </div> 

내가 입력 할 때 다른 사업부를 삽입 할 '@'

? 내가 어떻게 이걸 얻을 수 있니? 여기

내가 도와주세요

JSBIN을 시도하는 것이다. 미리 감사드립니다.

답변

2

이것은 저에게 효과적이었습니다. 방금 $ (this) .append (...)를 추가했습니다.

$("#target").keydown(function(e) { 

// console.log(e, String.fromCharCode(e.which)); 

    if(e.which === 50 && e.shiftKey === true){ 
     if(flag === true){ 
     flag = false;  
     return; 
     }  
     flag = true; 
    $(this).append('<div id="target2" contenteditable="true">New Div</div>'); 
     //console.log($('#target'),$('#target').prop('selectionStart')); 
    } 
}); 
+0

입니다 ... 새로운 사업부는 오히려 커서 위치에 추가보다 childNode에로 추가됩니다. .. 만약 내가 문자열 사이에 '@'를 입력하면, 나는 새 div가 커서 위치에 추가되기를 원한다. 방법이 있습니까 ?? – selvagsz

0

onKeyDown 이벤트 리스너를 수정했습니다. 대상과 동일한 id를 div에 keydown 이벤트를 바인딩합니다.

희망이 도움이 될 것입니다. http://jsbin.com/ilikay/4/edit

1

하나의 옵션은 '@'문자에서 keydown 이벤트를 감지 한 다음 절대 위치 지정 div를 현재 커서 위치에 배치하는 것입니다.

커서 위치를 가져 오는 것은 알맞은 코드입니다. 운 좋게도, 누군가 이미 그것을 썼다.

function getTextAreaXandY() { 



    // Don't do anything if key pressed is left arrow 
    if (e.which == 37) return;  

    // Save selection start 
    var selection = $(this).getSelection(); 
    var index = selection.start; 

    // Copy text to div 
    $(this).blur(); 
    $("div").text($(this).val()); 

    // Get current character 
    $(this).setSelection(index, index + 1); 
    currentcharacter = $(this).getSelection().text; 

    // Get previous character 
    $(this).setSelection(index - 1, index) 
    previouscharacter = $(this).getSelection().text; 

    var start, endchar; 
    var end = 0; 
    var range = rangy.createRange(); 

    // If current or previous character is a space or a line break, find the next word and wrap it in a span 
    var linebreak = previouscharacter.match(/(\r\n|\n|\r)/gm) == undefined ? false : true; 

    if (previouscharacter == ' ' || currentcharacter == ' ' || linebreak) { 
     i = index + 1; // Start at the end of the current space   
     while (endchar != ' ' && end < $(this).val().length) { 
      i++; 
      $(this).setSelection(i, i + 1) 
      var sel = $(this).getSelection(); 
      endchar = sel.text; 
      end = sel.start; 
     } 

     range.setStart($("div")[0].childNodes[0], index); 
     range.setEnd($("div")[0].childNodes[0], end); 
     var nextword = range.toHtml(); 
     range.deleteContents(); 
     var position = $("<span id='nextword'>" + nextword + "</span>")[0]; 
     range.insertNode(position); 
     var nextwordtop = $("#nextword").position().top; 
    } 

    // Insert `#caret` at the position of the caret 
    range.setStart($("div")[0].childNodes[0], index); 
    var caret = $("<span id='caret'></span>")[0]; 
    range.insertNode(caret); 
    var carettop = $("#caret").position().top; 

    // If preceding character is a space, wrap it in a span 
    if (previouscharacter == ' ') { 
     range.setStart($("div")[0].childNodes[0], index - 1); 
     range.setEnd($("div")[0].childNodes[0], index); 
     var prevchar = $("<span id='prevchar'></span>")[0]; 
     range.insertNode(prevchar); 
     var prevchartop = $("#prevchar").position().top; 
    } 

    // Set textarea selection back to selection start 
    $(this).focus(); 
    $(this).setSelection(index, selection.end); 

    // If the top value of the previous character span is not equal to the top value of the next word, 
    // there must have been some wrapping going on, the previous character was a space, so the wrapping 
    // would have occured after this space, its safe to assume that the left and top value of `#nextword` 
    // indicate the caret position 
    if (prevchartop != undefined && prevchartop != nextwordtop) { 
     $("label").text('X: ' + $("#nextword").position().left + 'px, Y: ' + $("#nextword").position().top); 
     $('ul').css('left', ($("#nextword").position().left) + 'px'); 
     $('ul').css('top', ($("#nextword").position().top + 13) + 'px'); 
    } 
    // if not, then there was no wrapping, we can take the left and the top value from `#caret`  
    else { 
     $("label").text('X: ' + $("#caret").position().left + 'px, Y: ' + $("#caret").position().top); 
     $('ul').css('left', ($("#caret").position().left) + 'px'); 
     $('ul').css('top', ($("#caret").position().top + 14) + 'px'); 
    } 

    $('ul').css('display', 'block'); 
} 

$("textarea").click(getTextAreaXandY); 
$("textarea").keyup(getTextAreaXandY); 

그들의 바이올린이 here이며,이 바이올린은 현재 커서 위치에 새로운 사업부를 배치 this question.

에 대한 응답에 포함 기록 된 다음과 같이 코드입니다.

-1

마지막

  1. 가 지정한 selectionStart에게
  2. 슬라이스 문자열에서를 사용하여 텍스트 영역의 커서 위치에서 문자열의 인덱스를 가져옵니다 ... 내가 그것을 어떻게이 ... 그것에 도달 할 수있는 방법을했다 0을 커서 위치에 놓습니다.
  3. span에 여러 개의 테두리 상자가 있으므로 span에 삽입하십시오.
  4. 보기 포트를 기준으로 element.getClientRects()를 사용하여 테두리 상자의 크기를 가져옵니다.
  5. 상단을 계산하고 왼쪽이 모든 최신 브라우저에서 작동 드롭 다운

에 공급 (여기 MDN Reference입니다). 낡은

에서 테스트하지 않은 것은 여기에 커서 지점에서 DIV를 배치하지 않습니다() 추가 사용 Working bin

+0

나는 아래 투표가 ... 왜인지 알 수 있습니까? – selvagsz

관련 문제