使用Javascript缩进选定的文本

时间:2009-08-09 04:36:54

标签: javascript

如何使用JavaScript缩进textarea控件中所选文本的每一行。类似于 Stack Overflow 编辑器的代码示例按钮。

更新:查看的代码,我写了一个解决方案,但只适用于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>

2 个答案:

答案 0 :(得分:2)

这对我在firefox上有用,没有机会在其他浏览器上测试它:

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>
[...]

更新:跨平台解决方案!

查找here一个同样适用于IE6的textarea缩进脚本 - 虽然我没有在IE7上测试它.. 致谢:我只是简单地将Kiewic的代码与getTextAreaSelection函数合并在Jerson Maglasang's blog上找到。

答案 1 :(得分:-2)

除非它是一个装扮成文本区域的div,否则我必须使用一堆空白区域