如何縮進使用JavaScript在textarea控件中選定文本的每一行。類似於代碼示例按鈕的堆棧溢出的編輯器。使用Javascript縮進選定文本
UPDATE:查看的而的代碼,我寫了一個解決方案,但僅與Firefox(也)的作品。
的功能是:
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 .. :) – 2009-08-10 10:34:31