2009-08-09 60 views
0

如何縮進使用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> 
+0

查找下面的解決方案,也支持IE6 .. :) – 2009-08-10 10:34:31

回答

-2

除非它被打扮成一個textarea一個div你將不得不使用一堆空的空間,我想

+1

我想,你錯了。 textarea的行爲就像一個pre元素,也就是說,它在內容中顯示*每個*空格。 – Boldewyn 2009-08-09 18:00:57

+0

同意它是空的空間 - 這是晚上晚,讓我修復評論 – Bostone 2009-08-09 20:14:41

+0

對不起,我仍然沒有得到你的答案的重點... – Boldewyn 2009-08-12 07:38:43

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

UPDATE:跨平臺的解決方案!

查找here一個文本縮進腳本,工作也IE6 - 我不是在IE7測試它,但.. 積分:我簡單地合併Kiewic的代碼與Jerson Maglasang's blog發現getTextAreaSelection功能。

+0

拆分和連接方法:你真的使用空字符串或您的文本只是一個受害者SO編輯? – Boldewyn 2009-08-09 18:02:10

+0

不,這些確實是空的字符串...順便說一句:我其實很喜歡SO編輯器! – 2009-08-09 18:48:53

+0

我想縮進每行的開始,而不僅僅是選擇的開始,但是你的代碼對我來說很有用。謝謝! – kiewic 2009-08-09 21:17:39