我想实现一个效果就是在textarea中输入一个@然后在该文字的右下方出现一个div,里面是放一个列表的,跟QQ的输入一样,不管是复制还是直接输入的@都出现这个功能
大神!大神!快出来~~~~~~~

如何实现textarea中输入@在右下方出现一个div
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
11条回答 默认 最新
- hfhan_872914334 2018-02-07 03:22关注
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{padding:0;margin:0;} .box{position:relatuve;} #ipt{ font-size:16px; padding-left:5px; height:30px; line-height:30px; } #list{ position:absolute; list-style:none; width:150px; display:none; } #list li{height:25px;line-height:25px;} #list li:hover{background:#efefef;cursor:pointer;} </style> </head> <body> <div class='box'> <input type="text" id='ipt'> <ul id='list'> <li>qq.com</li><li>sina.com</li><li>163.com</li> </ul> </div> <script> var ipt = document.getElementById('ipt'); var list = document.getElementById('list'); ipt.oninput = function(e){ //console.log(e) //获取光标位置 var position = getPosition(ipt); console.log(position,(ipt.value+'').length) //如果光标在文本最后面,且最后一个是@ if((position == (ipt.value+'').length) && /@$/.test(ipt.value)){ //把双字节的替换成两个单字节的然后再获得长度 var len = (ipt.value || '').replace(/[^\x00-\xff]/g,"01").length/2; var fz = parseFloat(window.getComputedStyle(ipt).fontSize); var wd = parseFloat(window.getComputedStyle(ipt).width); list.style.left = fz*len>wd?wd:fz*len + "px"; list.style.display = "block"; }else{ list.style.display = "none"; } } for(var i=0;i<list.children.length;i++){ list.children[i].onclick = function(e){ ipt.value += e.target.innerHTML; list.style.display = "none"; } } //输入框获取光标 function getPosition(element) { var cursorPos = 0; if (document.selection) {//IE var selectRange = document.selection.createRange(); selectRange.moveStart('character', -element.value.length); cursorPos = selectRange.text.length; } else if (element.selectionStart || element.selectionStart == '0') { cursorPos = element.selectionStart; } return cursorPos; } </script> </body> </html>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报