模拟实现文本框光标效果代码实例
分类:实例代码
分享一段代码实例,它模拟实现了文本框光标效果。
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <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>
模拟实现文本框光标效果代码实例,这样的场景在实际项目中还是用的比较多的,关于模拟实现文本框光标效果代码实例就介绍到这了。
模拟实现文本框光标效果代码实例属于前端实例代码,有关更多实例代码大家可以查看。