jquery 在输入框中输入时如何移动自定义文本光标?

7jmck4yq  于 2023-08-04  发布在  jQuery
关注(0)|答案(1)|浏览(106)

在输入框中输入时如何移动自定义文本光标?

.cursor {
  position: relative;
}

.cursor i {
  position: absolute;
  width: 10px;
  height: 80%;
  background-color: blue;
  left: 5px;
  top: 10%;
  animation-name: blink;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  opacity: 1;
}

@keyframes blink {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.5;
  }
}

个字符
虽然这成功地创建了一个 Flink 的、矩形的和蓝色的文本光标,但是一旦我在输入框中键入文本,它就保持在相同的位置。如何修改上面的代码,使光标移动,类似于Mac/Linux终端?

emeijp43

emeijp431#

您需要获取输入的值并将其放入隐藏的div中以获取clientWidth
请确保为输入和div“mask”设置相同的字体系列和相同的字体大小,以使其正常工作。
我添加了+3 px以进行更正。
我使用css css()来实现左移。

let elemDiv = document.getElementById("mask"),
  elemInput = document.getElementById("typing");

elemInput.oninput = function() {
  elemDiv.innerText = elemInput.value;
  
  // css version
  $(".cursor i").css({"left":(elemDiv.clientWidth + 3) + "px"});
  
  // debug infos 
  console.clear();
  console.log((elemDiv.clientWidth + 3) + "px");
}
.cursor {
  position: relative;
}
.cursor i {
  position: absolute;
  width: 10px;
  height: 80%;
  background-color: blue;
  left: 5px;
  top: 10%;
  animation-name: blink;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  opacity: 1;
}

#typing {
  width:100%;
  font-family:arial;
  font-size:12px;
}

#mask {
  font-family:arial;
  font-size:12px;
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}

@keyframes blink {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.5;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
<input type="text" id="typing" />
<i></i>
</div>
<div id='mask'></div>

但是你也可以用animate()来做。

let elemDiv = document.getElementById("mask"),
  elemInput = document.getElementById("typing");

elemInput.oninput = function() {
  elemDiv.innerText = elemInput.value;
  
  // animated version
  $(".cursor i").animate({"left":(elemDiv.clientWidth + 3) + "px"}, 50);
  
  // debug infos 
  console.clear();
  console.log((elemDiv.clientWidth + 3) + "px");
}
.cursor {
  position: relative;
}
.cursor i {
  position: absolute;
  width: 10px;
  height: 80%;
  background-color: blue;
  left: 5px;
  top: 10%;
  animation-name: blink;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  opacity: 1;
}

#typing {
  width:100%;
  font-family:arial;
  font-size:12px;
}

#mask {
  font-family:arial;
  font-size:12px;
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}

@keyframes blink {
  from {
    opacity: 1;
  }
  to {
    opacity: 0.5;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor">
<input type="text" id="typing" />
<i></i>
</div>
<div id='mask'></div>

相关问题