【发布时间】:2021-10-24 17:18:10
【问题描述】:
我正在制作一个假输入框,因此我可以应用复古风格的文本光标,例如 cmd _。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function copy(val){
$(".copy").html(val);
$(".vintage").css("left",val.length*1.5+"ch");}
function enterCmd(e){
if(event.keyCode==13){
$('.cmdBox').val("");
copy($('.cmdBox').val());}}
</script>
<!--So as the length of the string increases the cursor should move back and forth respectively.
But it starts out accurately and then drifts away-->
<div class="cmdBoxy" >><span class="copy" ></span>
<div class="vintage blink"></div>
</div>
<input type="text" class="cmdBox" oninput="copy($('.cmdBox').val());" id="lp" onkeydown="enterCmd($('.cmdBox'))">
<style>
.vintage{
position:relative;
background-color:white;
height:25%;
width:2%;
left:1.5%;
font-size:1em;}
.cmdBoxy{
position:relative;
top:1rem;
background-color:red;
height:1.5rem;
width:99%;}
</style>
如何使光标与文本同步移动
【问题讨论】:
-
为什么不改为
contenteditable? -
单个字符没有固定的宽度,因为它们在不同字符和不同字体之间都是不同的。你会得到最接近的是
1ch的 monopsace 字体.. -
也就是说,
cmd看起来很像很可能会使用等宽字体。 -
@SebastianSimon
contenteditable有什么帮助? -
@SebastianSimon 好吧,这只是将 div 向下推
<div><span contenteditable="true" >text here</span><div style="height:20px;width:20px;background-color:red;"></div></div>,为什么当接收输入的跨度增大时它不起作用?
标签: javascript html jquery css char