2009-08-09 3 views
0

JavaScript를 사용하여 텍스트 영역 컨트롤에서 선택한 텍스트의 각 행을 들여 쓰려면 어떻게해야합니까? 뭔가 코드 샘플의 스택 오버플로의 편집기와 비슷합니다.자바 스크립트로 선택된 텍스트 들여 쓰기

UPDATE : 그리고의 코드를보기는, 나는 해결책을 썼다,하지만 파이어 폭스 (도)와 함께 작동합니다.

기능

은 다음과 같습니다

function indentSelection() { 
    var selection, newValue; 
    var txt = document.getElementById("txt"); 
    var start = txt.selectionStart; 
    var end = txt.selectionEnd; 
    // extend the selecction start until the previous line feed 
    start = txt.value.lastIndexOf("\n", start); 
    // if there isn't a line feed before, 
    // then extend the selection until the begging of the text 
    if (start == -1) { 
     start = 0; 
    } 
    // if the selection ends with a line feed, 
    // remove it from the selection 
    if (txt.value.charAt(end - 1) == "\n") { 
     end = end - 1; 
    } 
    // extend the selection end until the next line feed 
    end = txt.value.indexOf("\n", end); 
    // if there isn't a line feed after, 
    // then extend the selection end until the end of the text 
    if (end == -1) { 
     end = txt.value.length; 
    } 
    // move the selection to a new variable 
    selection = txt.value.substring(start, end); 
    // add four spaces before line feeds 
    selection = selection.replace(/^(?=.+)/mg, " "); 
    // rebuild the textarea content 
    newValue = txt.value.substring(0, start); 
    newValue += selection; 
    newValue += txt.value.substring(end); 
    txt.value = newValue; 
} 

예는 수 :

<textarea id="txt" cols="80" rows="8">bla bla bla 
bla bla bla 
bla bla bla 
bla bla bla</textarea> 
<a href="#" onclick="indentSelection();return false;">indent selection!</a> 
+0

IE6도 지원하는 솔루션을 찾으십시오. :) –

답변

-2

당신이 내가

을 가정 빈 공간의 무리를 사용하는 것 텍스트 영역으로 옷을 입고있다 사업부 아니라면
+1

당신이 틀렸다고 생각합니다. 텍스트 영역은 사전 요소처럼 동작합니다. 즉, 내용에 * 모든 공백이 표시됩니다. – Boldewyn

+0

그것은 빈 공간입니다 - 어젯밤 늦었어요, 덧글을 수정하자 – Bostone

+0

죄송합니다, 아직 답변에 요점을 얻지 못했습니다 ... – Boldewyn

2

다른 브라우저에서 테스트 할 수있는 기회가 없습니다. 다른 브라우저에서 테스트 할 수있는 기회가 없습니다.

function indent_selection(){ 
var sel_start=document.getElementById("txt").selectionStart; 
var txt=document.getElementById("txt").value; 
var new_txt = txt.split(""); 
new_txt.splice(sel_start,0," "); 
document.getElementById("txt").value=new_txt.join(""); 

}

HTML :

[...] 
    <textarea id="txt">bla bla bla....</textarea> 
    <a href="#" onclick="indent_selection();">indent selection!</a> 
[...] 

UPDATE : 크로스 플랫폼 솔루션!

는 IE6도 작동 here 텍스트 영역 들여 스크립트를 찾기 - 그래도 난 IE7에 테스트하지했습니다 .. 크레딧 : 단순히 Jerson Maglasang's blog에있는 getTextAreaSelection 기능 Kiewic의 코드를 통합했습니다.

+0

분할 및 조인 방법 : 실제로 빈 문자열을 사용합니까, 아니면 텍스트를 희생합니다. SO 편집장? – Boldewyn

+0

아니요, 이것들은 정말로 빈 문자열입니다 ... BTW : 나는 실제로 SO 편집기를 정말 좋아합니다! –

+0

선택 영역의 시작 부분뿐만 아니라 각 행의 시작 부분을 들여 쓰고 싶지만 코드가 유용합니다. 감사! – kiewic

관련 문제