如何使用简单的 css、js 更改输入闪烁插入符号样式

Tah*_*hir 2 css caret input-field

我想知道如何使用 css/javascript 来调整 CSS 搜索框中闪烁的光标?

在此输入图像描述

是否可以将默认的闪烁插入符号替换为水平闪烁图标

Dan*_*rov 5

我不认为这有多难。我做了一个简单的例子,它适用于除 Safari 之外的大多数现代浏览器。它将插入符号绘制在画布上,并将其设置为输入的背景,位置是根据浏览器插入符号位置计算的。

它检查浏览器是否支持caret-colorcss 属性,如果不支持,则不会执行任何操作,因为系统插入符和我们的插入符将同时可见。从我测试的浏览器来看,只有Safari不支持。

$("input").on('change blur mouseup focus keydown keyup', function(evt) {
  var $el = $(evt.target);
  //check if the carret can be hidden
  //AFAIK from the modern mainstream browsers
  //only Safari doesn't support caret-color
  if (!$el.css("caret-color")) return;
  var caretIndex = $el[0].selectionStart;
  var textBeforeCarret = $el.val().substring(0, caretIndex);

  var bgr = getBackgroundStyle($el, textBeforeCarret);
  $el.css("background", bgr);
  clearInterval(window.blinkInterval);
  //just an examplethis should be in a module scope, not on window level
  window.blinkInterval = setInterval(blink, 600);
})

function blink() {
 
  $("input").each((index, el) => {
    var $el = $(el);
    if ($el.css("background-blend-mode") != "normal") {
      $el.css("background-blend-mode", "normal");
    } else {
      $el.css("background-blend-mode", "color-burn");
    }
  });
}


function getBackgroundStyle($el, text) {
  var fontSize = $el.css("font-size");
  var fontFamily = $el.css("font-family");

  var font = fontSize + " " + fontFamily;
  var canvas = $el.data("carretCanvas");
  //cache the canvas for performance reasons
  //it is a good idea to invalidate if the input size changes because of the browser text resize/zoom)
  if (canvas == null) {
    canvas = document.createElement("canvas");
    $el.data("carretCanvas", canvas);
    var ctx = canvas.getContext("2d");
    ctx.font = font;
    ctx.strokeStyle = $el.css("color");
    ctx.lineWidth = Math.ceil(parseInt(fontSize) / 5);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    //aproximate width of the caret
    ctx.lineTo(parseInt(fontSize) / 2, 0);
    ctx.stroke();
  }
  var offsetLeft = canvas.getContext("2d").measureText(text).width + parseInt($el.css("padding-left"));
  return "#fff url(" + canvas.toDataURL() + ") no-repeat " +
    (offsetLeft - $el.scrollLeft()) + "px " +
    ($el.height() + parseInt($el.css("padding-top"))) + "px";
}
Run Code Online (Sandbox Code Playgroud)
input {
  caret-color: transparent;
  padding: 3px;
  font-size: 15px;
  color: #2795EE;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Run Code Online (Sandbox Code Playgroud)

如果有兴趣,我可以稍微清理一下并将其包装在 jQuery 插件中。

编辑:忘记了闪烁,所以我添加了它。更好的方法是将其添加为 css 动画,在这种情况下,插入符应该位于位于输入上方的单独 html 元素中。