html 不显示tab缩进,HTML表单,make tab键触发缩进?

本文介绍了一种在文本区域中使用Tab键实现缩进的方法,并提供了完整的JavaScript代码实现,包括获取光标位置、设置光标位置等实用功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跟踪关键代码并向元素添加4个空格应该这样做。按Tab键时可以阻止默认值。像这样?:

在所有评论后编辑:

啊,好的,所以你实际上要求几个JS函数(在文本区域中获取光标位置,更改文本,在文本区域中设置光标位置)。多一点环顾四周会给你所有这些,但因为我是一个好人,我会把它放在那里为你。其他答案可以在this post about getCursorPosition()和this post about setCursorPosition()中找到。我为你更新了jsFiddle。这是代码更新

$('#myarea').on('keydown', function(e) {

var thecode = e.keyCode || e.which;

if (thecode == 9) {

e.preventDefault();

var html = $('#myarea').val();

var pos = $('#myarea').getCursorPosition(); // get cursor position

var prepend = html.substring(0,pos);

var append = html.replace(prepend,'');

var newVal = prepend+' '+append;

$('#myarea').val(newVal);

$('#myarea').setCursorPosition(pos+4);

}

});

new function($) {

$.fn.getCursorPosition = function() {

var pos = 0;

var el = $(this).get(0);

// IE Support

if (document.selection) {

el.focus();

var Sel = document.selection.createRange();

var SelLength = document.selection.createRange().text.length;

Sel.moveStart('character', -el.value.length);

pos = Sel.text.length - SelLength;

}

// Firefox support

else if (el.selectionStart || el.selectionStart == '0')

pos = el.selectionStart;

return pos;

}

} (jQuery);

new function($) {

$.fn.setCursorPosition = function(pos) {

if ($(this).get(0).setSelectionRange) {

$(this).get(0).setSelectionRange(pos, pos);

} else if ($(this).get(0).createTextRange) {

var range = $(this).get(0).createTextRange();

range.collapse(true);

range.moveEnd('character', pos);

range.moveStart('character', pos);

range.select();

}

}

}(jQuery);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值