使用 jQuery,如何在编辑文本框时启用智能引号的实时插入?
maxhawkins
问问题
1843 次
3 回答
8
于 2009-01-18T02:02:38.257 回答
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'));
于 2009-01-18T13:50:08.057 回答
5
以 Kent 的回答为基础:您可以使用 q 标签,但是,大多数浏览器默认只使用直引号,而 IE 不显示任何引号。
这在 IE7+ 和其他浏览器中通过使用 CSS 得到了补救。这是我在样式表中添加的内容:
q:before {
content: "\201c";
}
q:after {
content: "\201d";
}
q q:before {
content: "\2018";
}
q q:after {
content: "\2019";
}
第一批用于大弯双引号,第二批用于大弯单引号(用于嵌套 q 标签时)。
这在 IE6 中不起作用。我的正常解决方案是在 q 元素上设置颜色,以便它们脱颖而出。我对 IE6 的“去他妈的,这就够了”策略的一部分。
于 2009-01-18T14:47:51.043 回答