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>
IE6도 지원하는 솔루션을 찾으십시오. :) –