如何在HTML输入字段中使用此方形光标?

xRo*_*bot 21 html javascript css xhtml cursor

如何在输入标签中使用此方形光标(下图)?

C:\维基百科

ale*_*lex 36

样品

样品

改变了它的工作方式,似乎解决了一些问题:)

  • 接受正常输入可以的任何文本
  • Backspace工作
  • 理论上可以支持粘贴文本

通常需要注意的是,最明显的是无法直观地看到插入符号的位置.

基于其缺点和可用性问题,我认为这个解决方案是否值得实施是多么困难.

$(function() {
  var cursor;
  $('#cmd').click(function() {
    $('input').focus();
    cursor = window.setInterval(function() {
      if ($('#cursor').css('visibility') === 'visible') {
        $('#cursor').css({
          visibility: 'hidden'
        });
      } else {
        $('#cursor').css({
          visibility: 'visible'
        });
      }
    }, 500);

  });

  $('input').keyup(function() {
    $('#cmd span').text($(this).val());
  });

  $('input').blur(function() {
    clearInterval(cursor);
    $('#cursor').css({
      visibility: 'visible'
    });
  });
});
Run Code Online (Sandbox Code Playgroud)
#cmd {
  font-family: courier;
  font-size: 14px;
  background: black;
  color: #21f838;
  padding: 5px;
  overflow: hidden;
}
#cmd span {
  float: left;
  padding-left: 3px;
  white-space: pre;
}
#cursor {
  float: left;
  width: 5px;
  height: 14px;
  background: #21f838;
}
input {
  width: 0;
  height: 0;
  opacity: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cmd">
  <span></span>
  <div id="cursor"></div>
</div>

<input type="text" name="command" value="" />
Run Code Online (Sandbox Code Playgroud)

  • 还有三个基本问题:一,光标不能放在文本末尾以外的任何地方; 二,`keyup`(或`keydown`)事件的`keyCode`属性不是字符代码,不应该这样对待.仅使用`keypress`事件处理文本输入; 三,这不是表单输入,因此无法提交给服务器.您需要一个隐藏的输入,它会自动与div的内容保持同步. (2认同)
  • 使用现代浏览器,您可以使用selectionEnd属性来确定光标的位置.我这里有一个小提琴,支持任意光标定位:http://jsfiddle.net/HugeHugh/gZMSQ/ (2认同)

Dan*_*ger 5

公认的解决方案有很多问题:

  • 它非常缓慢,尤其是在按住按键时。

  • 真正的插入符号可以用箭头移动,但你不会看到它在哪里,因为假方块总是在最后。

  • 输入需要通过单击再次手动聚焦。

  • 无法正确选择文本,因为一旦释放鼠标按钮,选择就会丢失,并且完全不可能使用键盘选择文本。

一个更好的解决方案可能是使用 CSS 来确保“插入符号”元素总是出现在contenteditable“输入”之后,并且使用 JS 来确保contenteditable元素始终处于焦点状态。您可能会尝试通过添加autofocuscontenteditable元素并<label>为插入符号元素使用 a来完成最后一件事,但这不适用于contenteditable元素。注意不需要键盘事件监听器:

const input = document.getElementById('input');
const caret = document.getElementById('caret');

// Move the focus back to the input if it moves away from it:
input.addEventListener('blur', (e) => {  
  input.focus();
});

// Set the focus to the input so that you can start typing straight away:
input.focus();
Run Code Online (Sandbox Code Playgroud)
body {
  background: #000;
  color: #0F0;
  font-family: monospace;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: scroll;
  margin: 0;
  padding: 16px;
}

#input {
  display: inline;
  word-break: break-all;
  outline: none;
  visibility: visible;
}

#caret {
  border: 0;
  padding: 0;
  outline: none;
  background-color: #0F0;
  display: inline-block;
  font-family: monospace;
}
Run Code Online (Sandbox Code Playgroud)
C:\WIKIPEDIA > 

<div id="input" contenteditable="true"></div><button id="caret" for="input">&nbsp;</button>
Run Code Online (Sandbox Code Playgroud)

在更现实的示例中,您可能希望:

  • 避免在contenteditable元素中捕获焦点,因为这会阻止选择以前的命令。相反,contenteditable只有在用户按下某个键时才聚焦到元素。

  • 根据位置显示不同的插入符号:如果它在输入的末尾,则为方形,如果它在其他地方则为 line(除非使用Ins键启用了改写模式)。

  • 如果?按下,则添加新命令/条目。

  • 防止输入格式化文本并在需要时自动将其拆分为多个命令/条目。

const history = document.getElementById('history');
const input = document.getElementById('input');
const cursor = document.getElementById('cursor');

function focusAndMoveCursorToTheEnd(e) {  
  input.focus();
  
  const range = document.createRange();
  const selection = window.getSelection();
  const { childNodes } = input;
  const lastChildNode = childNodes && childNodes.length - 1;
  
  range.selectNodeContents(lastChildNode === -1 ? input : childNodes[lastChildNode]);
  range.collapse(false);

  selection.removeAllRanges();
  selection.addRange(range);
}

function handleCommand(command) {
  const line = document.createElement('DIV');
  
  line.textContent = `C:\\WIKIPEDIA > ${ command }`;
  
  history.appendChild(line);
}

// Every time the selection changes, add or remove the .noCursor
// class to show or hide, respectively, the bug square cursor.
// Note this function could also be used to enforce showing always
// a big square cursor by always selecting 1 chracter from the current
// cursor position, unless it's already at the end, in which case the
// #cursor element should be displayed instead.
document.addEventListener('selectionchange', () => {
  if (document.activeElement.id !== 'input') return;
  
  const range = window.getSelection().getRangeAt(0);
  const start = range.startOffset;
  const end = range.endOffset;
  const length = input.textContent.length;
  
  if (end < length) {
    input.classList.add('noCaret');
  } else {
    input.classList.remove('noCaret');
  }
});

input.addEventListener('input', () => {    
  // If we paste HTML, format it as plain text and break it up
  // input individual lines/commands:
  if (input.childElementCount > 0) {
    const lines = input.innerText.replace(/\n$/, '').split('\n');
    const lastLine = lines[lines.length - 1];
    
    for (let i = 0; i <= lines.length - 2; ++i) {
      handleCommand(lines[i]);
    }
  
    input.textContent = lastLine;
    
    focusAndMoveCursorToTheEnd();
  }
  
  // If we delete everything, display the square caret again:
  if (input.innerText.length === 0) {
    input.classList.remove('noCaret');  
  }  
});

document.addEventListener('keydown', (e) => {   
  // If some key is pressed outside the input, focus it and move the cursor
  // to the end:
  if (e.target !== input) focusAndMoveCursorToTheEnd();
});

input.addEventListener('keydown', (e) => {    
  if (e.key === 'Enter') {
    e.preventDefault();
        
    handleCommand(input.textContent);    
    input.textContent = '';
    focusAndMoveCursorToTheEnd();
  }
});

// Set the focus to the input so that you can start typing straigh away:
input.focus();
Run Code Online (Sandbox Code Playgroud)
body {
  background: #000;
  color: #0F0;
  font-family: monospace;
  height: 100vh;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: scroll;
  word-break: break-all;
  margin: 0;
  padding: 16px;
}

#input {
  display: inline;
  outline: none;
  visibility: visible;
}

/*
  If you press the Insert key, the vertical line caret will automatically
  be replaced by a one-character selection.
*/
#input::selection {
  color: #000;
  background: #0F0;
}

#input:empty::before {
  content: ' ';
}

@keyframes blink {
  to {
    visibility: hidden;
  }
}

#input:focus + #caret {
  animation: blink 1s steps(5, start) infinite;
}

#input.noCaret + #caret {
  visibility: hidden;
}

#caret {
  border: 0;
  padding: 0;
  outline: none;
  background-color: #0F0;
  display: inline-block;
  font-family: monospace;
}
Run Code Online (Sandbox Code Playgroud)
<div id="history"></div>

C:\WIKIPEDIA > 

<div id="input" contenteditable="true"></div><button id="caret" for="input">&nbsp;</button>
Run Code Online (Sandbox Code Playgroud)

在一般情况下,它通常是一个坏主意,监听键盘事件(keydown/ keypress/ keyup)来处理文本输入或光标,作为输入的值也可以通过粘贴或删除文本也被更新,有很多优势的情况下,如箭头、删除、转义、全选、复制、粘贴等快捷方式……因此,尝试列出我们应该处理的所有键的详尽列表可能不是最好的方法。

此外,将无法在手机上正常工作,大多数按键发出相同的价值观e.key = 'Unidentified'e.which== 229e.keyCode = 229

相反,通常最好依赖其他事件,例如input和 用于KeyboardEvents处理非常特定的键,就像?在这种情况下一样。

如果您需要检查 KeyboardEvent 的属性值,例如e.key, e.codee.which或者e.keyCode您可以使用https://keyjs.dev。我会尽快添加有关这些跨浏览器不兼容的信息!

Key.js \ JavaScript KeyboardEvent 的键码和键标识符

免责声明:我是作者。