首页 > 解决方案 > 当我按下制表键时如何使可竞争的 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>

标签: javascripthtmljquerycss

解决方案


你可以创建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>


推荐阅读