我想实现一个效果就是在textarea中输入一个@然后在该文字的右下方出现一个div,里面是放一个列表的,跟QQ的输入一样,不管是复制还是直接输入的@都出现这个功能!(前两天回答的那些有bug的)图片说明
12条回答 默认 最新
- hfhan_872914334 2018-02-08 04:36关注
亲自试了下,应该是上取整。
你看这个可不可以,有什么问题可以私信我。<!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; 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'> <textarea rows="3" cols="100" id='ipt'></textarea> <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 iStyle = window.getComputedStyle(ipt); //把双字节的替换成两个单字节的然后再获得长度 var len = (ipt.value || '').replace(/[^\x00-\xff]/g,"01").length/2; var fz = parseFloat(iStyle.fontSize); var wd = parseFloat(iStyle.width); var lh = parseFloat(iStyle.lineHeight); list.style.left = fz*(len%wd)>wd?wd:fz*(len%wd) + "px"; list.style.top = Math.ceil(len/wd)*lh + "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>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用