模擬實現文字框游標效果程式碼例項

antzone發表於2017-04-18

分享一段程式碼例項,它模擬實現了文字框游標效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  font-family: 'sans-serif';
}
#inputText {
  position: relative;
  width: 300px;
  height: 30px;
  line-height: 30px;
}
#inputText .real {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
  -webkit-appearance: none;
  border: none;
  background: none;
  color: transparent;
  font-size: 14px;
}
#inputText .real::selection {
  background: none;
  color: transparent;
}
#inputText .display {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#inputText .display .showText {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #f00;
  font-size: 14px;
}
#inputText .display .cursorPosition {
  position: absolute;
  width: 1px;
  top: 0;
  bottom: 0;
  background: #0f0;
  margin-left: 2px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script>
$(function () {
  $('.real').on('keyup', function () {
    var $this = $(this);
    var value = $this.val()
    $('.showText').text(value);
    var selctionStart = $this[0].selectionStart;
    var p = new RegExp(/[^\u4e00-\u9fa5]/g);
    var zhL = value.replace(p, '').length;
    $('.cursorPosition').stop(true, true).animate({
      'left': ((value.length - zhL) + zhL * 2) * 7
    });
  });
})
</script>
</head>
<body>
  <div id="inputText">
    <div class="display">
      <div class="showText"></div>
      <div class="cursorPosition"></div>
      <div class="range"></div>
    </div>
    <input class="real" />
  </div>
</body>
</html>

相關文章