caret-color 可以设置光标颜色
caret-color: red;
但只能更改颜色,粗细位置不能更改,可以自定义光标,由于 input不能使用 ::after、::before 伪元素,所以可以用 div 自定义
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Cursor</title>
<style>
.custom-cursor {
position: relative;
padding-left: 5px;
caret-color: transparent;
display: inline-block;
width: 200px;
}
.custom-cursor:focus::after {
content: '';
position: absolute;
top: 5px;
width: 2px; /* 调整这个值来改变光标的“粗细” */
height: 63%;
background-color: red;
animation: blink 0.8s step-end infinite;
}
.insert-input {
display: inline-flex;
position: relative;
align-items: center;
input {
padding-left: 6px;
caret-color: transparent;
}
}
.insert-cursor {
position: absolute;
margin-left: 0px;
margin-top: -1px;
width: 2px; /* 调整这个值来改变光标的“粗细” */
height: 68%;
background-color: red;
opacity: 0;
}
.insert-input:has(.input-text:focus) {
.insert-cursor {
margin-left: 5.5px;
animation: blink 0.8s step-end infinite;
opacity: 1;
}
}
@keyframes blink {
from, to { background-color: transparent; }
50% { background-color: red; }
}
</style>
</head>
<body>
<div class="custom-cursor" contenteditable="true">在这里输入文本...</div><br>
<div class="insert-input">
<span class="insert-cursor"></span>
<input class="input-text" type="text" autocomplete="off" placeholder="请输入内容">
</div>
</body>
</html>
但是需要注意的是,用 div 做的输入框不安全,有被劫持风险,光标暂不可以像正常光标那样插入到指定位置,这需要监听光标点击事件,动态设置位置,input 光标位置不是放在输入文本后面,可能需要 js 动态设置位置,有待改善。可以参照 vscode 的源码,vscode 的光标是可以自定义的。