本文介绍了在TextArea中捕获选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有人知道一个跨浏览器,可靠的解决方案,用于在textarea字段中捕获tab键的按键,并替换(在正确的位置)4个空格? textarea用于输入一篇文章,需要这个功能。
Does anyone know a cross-browser, reliable solution for catching presses of the tab-key in a textarea field, and replacing (in the correct position) 4 spaces? The textarea is being used to input an essay, and needs this feature.
注意:我尝试过使用FCKEditor,其中没有捕获标签,并且有一些我不需要的功能。我想要一个简单的解决方案,只是为了捕捉标签。
Note: I tried using FCKEditor, among others, which did not catch tabs and had a bunch of features I didn't need. I want a simple solution just for catching tabs.
推荐答案
我没有广泛测试,但这似乎有用:
I didn't test extensively, but this seems to work:
(我在 )
<textarea id="text-area" rows="20" cols="100"></textarea>
<script>
document.getElementById("text-area").onkeydown = function(e) {
if (!e && event.keyCode == 9)
{
event.returnValue = false;
insertAtCursor(document.getElementById("text-area"), " ");
}
else if (e.keyCode == 9)
{
e.preventDefault();
insertAtCursor(document.getElementById("text-area"), " ");
}
};
//http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript#comment-3817
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
var temp;
myField.focus();
sel = document.selection.createRange();
temp = sel.text.length;
sel.text = myValue;
if (myValue.length == 0) {
sel.moveStart('character', myValue.length);
sel.moveEnd('character', myValue.length);
} else {
sel.moveStart('character', -myValue.length + temp);
}
sel.select();
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
}
}
</script>
编辑:修改了脚本,使其不使用jQuery。
EDIT: Modified the script so it doesn't use jQuery.
这篇关于在TextArea中捕获选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!