How to use this square cursor in a HTML input fiel

2019-01-07 16:55发布

问题:

How can I use this square cursor ( image below ) in the input tags ?

回答1:

Sample

I've changed how it works, and it seems to solve a few issues :)

  • Accepts any text a normal input can
  • Backspace works
  • Theoretically can support pasting text

Usual caveats apply still, most notably the inability to visually see where the caret is.

I'd think long and hard whether this solution is worth implementing, based on its drawbacks and usability issues.

$(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'
    });
  });
});
#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;
}
<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="" />



回答2:

AFAIK, that's not possible for html text box, you could style the input itself but you can do nothing about the cursor other than applying the cursor options that are already available :(



回答3:

For <input> tags, there's not much you can do. If you didn't mind it being a horrible hack, you could always use JavaScript to resize the text box as needed (set width = *something* * count), and have an <img> with the cursor to the right.

I don't think there are any less 'ugh' solutions, bar handling the text input yourself, which is probably overkill.



回答4:

you can't. which means: you could do it yourself by using a fixed-with font, use a blinking gif als background which position is set dynamicaly by calculating the with of the already typed text - but there will be the "normal" cursor above your gif, making this solution ugly



回答5:

You would have to 1) roll your own textbox and 2) hide the real cursor by continually focusing it elsewhere. Then, capture the key events at the document/body level, and insert that value into your own element. The cursor would then be an animated GIF that was always positioned at far right of your "textbox".

You will run into issues with #2, and the whole thing is generally inadvisable. HTML 5 opens up some new possibilities, but it's still an awful lot of work for a cursor.