2013-08-01 1 views
-1

내 편집기 영역에서 :자바 스크립트

<div id="myeditor" contenteditable="true"><div> 

나는 그것이 ID의 내 사업부에 "A"를 표시

$("#myeditor").text($("#myeditor").text() + String.fromCharCode(65)) 

를 사용하여 전송 및 디스플레이 키 코드 수 '명이 MyEditor '. 하지만 화살표 커서 키 코드를 보내는 데 막혔습니다. (왼쪽 37, 최대 38; 오른쪽 : 39; 아래 40)

$("#myeditor").text($("#myeditor").text() + String.fromCharCode(39)) 

이 작업 그다지 아 .. 그 목적이 arent (앰퍼샌드 인용 부호와 같은) 다른 ASCII 문자를 보이고있다. 그것을 할 수있는 올바른 방법을 말해 줄 수 있습니까?

답변

1

그 이유는 모든 다른 문자가 관련된 문자가있는 키의 문자이기 때문입니다. 그러나 화살표 키에는 ←, → 같은 문자가 없습니다. 그들은 단지 몇 가지 기능을 가지고 있습니다. 화살표 키를 사용하여 텍스트 상자에 화살표를 입력 한 적이 있습니까?

당신이 정말로 입력 화살표로 사용하려는 경우, 당신은 당신의 jQuery를에 다음을 수행 할 수 있습니다 ..

var element = $('#myeditor'), 
    elementText = element.text(); 
    store = { 
     37: "&larr;", 
     38: "&uarr;", 
     39: "&rarr;", 
     40: "&darr;" 
    }; 

element.keydown(function(event) { 
    var selection = window.getSelection().getRangeAt(0); 
     //getSelection gets the selected range of text, when nothing is selected,selection is empty.getRangeAt(0)makes selection from the start of selection. 
    var keyCode = event.which; 
    if(store[ keyCode ]) { 
     var n = document.createElement('span'); 
      //Adds a new html element. 
     n.innerHTML = store[keyCode]; 
      //Adds the arrow to the newly created html element. 
     selection.insertNode(n); 
      //insert the newly created html element. 
    } 
}); 

Demo Fiddle by Connor →

또는

+0

@Connor 더 나아 졌습니까? 그렇게하지 않으면 새로운 줄에 화살표가 추가됩니다. –

+1

훨씬 좋았어. 왜 아무 것도 변하지 않는'text'를 설정하고, ** http : //jsfiddle.net/eXr2n/3/** – iConnor

+0

으로 만든이 데모를 확인하고, code'var code = e.keyCode || ' – iConnor

0

내가 대신 String.fromCharCode을 사용 http://jsfiddle.net/ybPzP/10/ (0x2190) 자바 스크립트에서 왼쪽 화살표 문자를 비교할 수 있습니다. 이것을 경고하면 왼쪽 화살표 문자가 경고를받는 것을 볼 수 있습니다.

관련 문제