2009-01-18 20 views

回答

5

假設你正在談論試圖用自動智能引號替換「和」:它不一定是一個好主意的算法來選擇引號的正確途徑。面對的是脆弱的,很容易被愚弄,在引用前查看角色有一個常見的方法,這個方法被Office等程序所使用,但是他們經常犯錯誤,使得文本更糟糕,沒有嘗試過,有時候,你根本不需要聰明的語錄(尤其是在一個像這樣的網站,我們正在談論代碼)。

如果是爲了您自己的個人打字便利性,您可以嘗試安裝允許直接和明確鍵入智能報價的鍵盤佈局。

這就是說,如果你一定要,這裏的一些代碼開始...

<textarea id="foo" rows="6" cols="40"></textarea> 

...

function AutoReplacer(element) { 
    // List of replacement rules. Note currently with this simplistic code 
    // replacements should be the same length as the original text. 
    // 
    replacements= [ 
     [' "', ' \u201C'], 
     ['("', ' \u201C'], 
     ['"', '\u201D'] 
    ]; 

    // Only attempt to use replacer behaviour if we can retain the cursor 
    // position. Setting value by default moves the cursor to the end of the 
    // input, which is too irritating. 
    // 
    if (getInputSelection(element)!==null) { 
     element.onkeyup= function() { 
      value= element.value; 
      for (var i= 0; i<replacements.length; i++) { 
       value= value.split(replacements[i][0]).join(replacements[i][1]); 
      } 
      if (value!=element.value) { 
       var s= getInputSelection(element); 
       element.value= value; 
       setInputSelection(element, s); 
      } 
     }; 
    } 
} 

// Cross-browser (as much as possible anyway) cursor positioning 
// 
function getInputSelection(element) { 
    if (element.selectionStart!==window.undefined) { 
     return [element.selectionStart, element.selectionEnd]; 
    } else if (document.selection) { 
     var BIG= 1000000; 
     var range= document.selection.createRange(); 
     if (range.moveStart===window.undefined) 
      return [0, 0]; 
     var start= -range.moveStart('character', -BIG); 
     var end= -range.moveEnd('character', -BIG); 
     return [start-1, end-1]; 
    } else return null; 
} 
function setInputSelection(element, s) { 
    if (element.selectionStart!==window.undefined) { 
     element.selectionStart= s[0]; 
     element.selectionEnd= s[1]; 
    } else if (document.selection) { 
     var range= element.createTextRange(); 
     range.collapse(true); 
     range.moveEnd('character', s[1]); 
     range.moveStart('character', s[0]); 
     range.select(); 
    } 
} 

new AutoReplacer(document.getElementById('foo')); 
+0

當你需要用單引號(')替換爲' – 2012-02-03 15:25:11

8

一種選擇是使用'q'元素的小已知。

foo bar<q>quoted area</q>foo bar 

然後用戶代理將盡最大努力創建最佳風格的引號。

+0

非常酷,但太糟糕了,它不適用於IE。這將是很長的時間,直到它可用。 – 2009-01-18 02:22:50

5

要建立在肯特的回答是:你可以使用默認的Q標籤,但是,大多數瀏覽器默認只使用直引號,IE不顯示任何引號。

這可以通過使用CSS在IE7 +和其他瀏覽器中解決。下面是我把我的樣式表:

q:before { 
    content: "\201c"; 
} 
q:after { 
    content: "\201d"; 
} 
q q:before { 
    content: "\2018"; 
} 
q q:after { 
    content: "\2019"; 
} 

第一批是捲曲的雙引號,第二個是捲曲的單引號(當你嵌套q標籤)。

這不適用於IE6。我的常規解決方案是在q元素上設置一個顏色,使它們脫穎而出。作爲IE6的一部分,我認爲這已經足夠好了。

+0

+1'的顏色和「fck IE,它足夠好」時,這個工作原理相當乾淨。我之前使用過顏色,只是被遺忘了。 – 2009-01-19 10:48:31