javascript - 当我按下制表键时如何使可竞争的 div 做制表符间距
问题描述
当我按下制表键时,我试图让这个可竞争的 div 做制表符间距,但它不起作用。我希望有人能解决这个问题。您可以添加 id 或 class 或使其工作所需的任何内容。谢谢
div[contenteditable]{
display:inline-block;
font-family:lucida console;
font-size:12px;
line-height:14px;
white-space: pre;
padding:5px;
margin:0;
min-width:200px;
min-height:50px;
height:auto;
background:#fff;
border:1px solid #000;
}
<div contenteditable="true">dwdw wdw</div>
解决方案
你可以创建keydown
事件
我已经看到了一个功能,可以在按下 Tab 键时将插入符号放在文本的末尾。这在多个浏览器上运行
检查一下:contenteditable,在文本末尾设置插入符号(跨浏览器)
$('#test').on( 'keydown', function( e ) {
if( e.which == 9 ) {
e.preventDefault();
$(this).html($(this).html() + " ")
placeCaretAtEnd( document.querySelector('#test') );
}
} );
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
div[contenteditable]{
display:inline-block;
font-family:lucida console;
font-size:12px;
line-height:14px;
white-space: pre;
padding:5px;
margin:0;
min-width:200px;
min-height:50px;
height:auto;
background:#fff;
border:1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true" id="test">asdfsadf</div>
推荐阅读
- javascript - 汉堡菜单不显示 CSS、JS 和 HTML
- azure - 无法从逻辑应用连接到 SQL Server
- python - 来自范围的nD“立方体”
- c# - 如何通过 JSON 对象列表检查键的值是否相等
- android - 使用键值对创建新地图,而不是保存
- r - R包VennDiagram:如何在圆圈外打印值?
- cmake - 已安装的可执行文件在加载期间找不到共享库
- android - 应用程序在 Android 10 上崩溃(inflateException in layout/abc_screen_simple line #17)
- unity3d - 如何防止向上的刚体速度?
- reactjs - 在当前块之后添加新块的问题