Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Weibo @ function with Javascript

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "using Javascript to analyze Weibo @ function". In daily operation, I believe many people have doubts about using Javascript to analyze Weibo @ function. The editor has consulted all kinds of materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "using Javascript to analyze Weibo @ function"! Next, please follow the small series to learn together!

This function is analyzed as follows:

1. Determine the position of the cursor

2. Determine the string @ in the textarea text box

3. Tip pop-up event

4. Keyboard operation events

5. Ajax calls

6. Text insertion

There are other functions, of course.

Does it feel complicated to watch? It doesn't matter. We'll analyze it step by step.

First we need to determine the cursor position of the textarea. In W3C, getting the cursor position is relatively simple, you can use selectionStart and selectionEnd, IE browser does not support these two attributes, but IE has another document.selection object, which can simulate the same function. The code is as follows:

//first define a basic class to set some global variables function demonAt(opts) { this.elem=opts.elem; //textbox this.at= {}; //Temporarily save text box content interception attributes this.opt= {}; this.searched=""; //Used to determine whether the user input characters are the same as before, if so skip ajax this.url=opts.url; this.index=1; } //@ function of Weibo demonAt.prototype= { getCursor: function(elem) { var _this=this; var rangeData = { start: 0, end: 0, text: "" }; if(typeof(this.elem.selectionStart)=="number") {//W3C rangeData.start=this.elem.selectionStart;//cursor start position rangeData.end=this.elem.selectionEnd;//cursor end position rangeData.text=this.elem.value.substring(0,this.elem.selectionStart);//Get text box value } else if (document.selection) {//IE var sRange=document.selection.createRange(); var oRange=document.body.createTextRange(); oRange.moveToElementText(this.elem); rangeData.text=sRange.text; rangeData.bookmark = sRange.getBookmark(); for(i=0;oRange.compareEndPoints("StartToStart",sRange)

< 0 && sRange.moveStart("character", -1) !== 0; i ++) { if (this.elem.value.charAt(i) == '\r') { i ++;//IE的特殊处理,遇到enter键需要加1 } } rangeData.start=i; rangeDatarangeData.end = rangeData.text.length + rangeData.start; rangeData.text=this.elem.value.substring(0,i); } //alert(rangeData.text) return rangeData; }, setCursor: function(elem,start,end) {//设置光标 if(this.elem.setSelectionRange) {//W3C this.elem.setSelectionRange(start,end); } else if(this.elem.createRange) {//IE var range=this.elem.createRange(); if(this.elem.value.length==rangeData.start) { range.collapse(false); range.select(); } else { range.moveToBookmark(rangeData.bookmark); range.select(); } } }, add: function(elem,txtData,nStart, nLen) {//插入文本参数操作的元素,数据,起始坐标位置,用户输入字符长度 //this.setCursor(this.elem,this.rangeData); this.elem.focus(); var _range; if(this.elem.setSelectionRange) {//W3C _tValue=this.elem.value;//获取文本框内容 var _start = nStart - nLen,//设置光标起点光标的位置-离@的文本长度 _end = _start + txtData.length,//设置光标末尾,start+数据文字长度 _value=_tValue.substring(0,_start)+txtData+" "+_tValue.substring(nStart, this.elem.value.length); this.elem.value=_value; this.setCursor(this.elem,_end+1,_end+1); } else if(this.elem.createTextRange) { _range=document.selection.createRange(); _range.moveStart("character", -nLen);//移动光标 _range.text = txtData+" "; } } } 自定义一个rangeData对象,保存光标的位置和textarea框内从光标位置到开始处的字符串;返回出来。这个对象在下面其他函数中会用到。根据光标位置的确定,可以书写文字插入函数add();有了上面的函数,我们可以对textarea框内@的字符判断,然后实现tip层定位和弹出,如果判断这个,我们可以用正则: var _reg=/@[^@\s]{1,20}$/g; 那么定位呢,若在textarea内判断是不现实的,因为我们无法获取正确的left和top值,所以这里需要模拟一个div层,将div插入到body 中,定位到与textarea相同的位置,然后获取到textarea内的文字,进行字符串的拆分,加上标签元素,这样可以获取到正确的位置。说的有点绕了,看下面代码能更直观的表达。 var _string=""+"@前面的文字"+""+"@"+""+"@后面的文字"+""; 看到这句,很多人应该理解做法,将这段append到上诉定位的div中,这样,我们可以通过标签获取到offset值了。于是我们写下面的代码: demonAt.prototype= { init: function() {//首先我们要初始化 var _body=$("body"); var _div=$(""), _tip=$(""); _body.append(_div); _body.append(_tip); var _left=$(this.elem).offset().left+"px", _top=$(this.elem).offset().top+"px", _width=$(this.elem).outerWidth()+"px", _height=$(this.elem).outerHeight()+"px", _lineHeight=$(this.elem).css("line-height"), _style="position:absolute;overflow:hidden;z-index:-9999;line-height:"+_lineHeight+";width:"+_width+";height:"+_height+";left:"+_left+";top:"+_top; _div.attr("style",_style); this.inset(); }, getAt: function() { var _rangeData=this.getCursor(); var k=_value=_rangeData.text.replace(/\r/g,"");//去掉换行符 var _reg=/@[^@\s]{1,20}$/g;//正则,获取value值后末尾含有@的并且在20字符内 var _string=""; if(_value.indexOf("@")>

= 0&&_value.match(_reg)) { var _postion=_rangeData.start; var _oValue=_value.match(_reg)[0];//找到value中***匹配的数据 var vReg=new RegExp("^"+_oValue+".*$","m");//跟数据匹配的正则 暂时保留 _value_value=_value.slice(0, _postion); //重写_value 字符串截取 从0截取到光标位置 if(/^@[a-zA-Z0-9\u4e00-\u9fa5_]+$/.test(_oValue)&& !/\s/.test(_oValue)) { this.at['m'] = _oValue_oValue = _oValue.slice(1);//用户输入的字符 如@颓废小魔,即"颓废小魔" this.at['l'] = _value.slice(0, -_oValue.length - 1); //@前面的文字 this.at['r'] = k.slice(_postion - _oValue.length, k.length);//@后面的文字 this.at['pos']=_postion;//光标位置 this.at['len']=_oValue.length;//光标位置至@的长度,如 @颓废小魔,即"颓废小魔"的长度 this.showTip(this.url) } else {//alert(1) this.hiddenTip() } } else { this.hiddenTip() } }, buidTip: function() {//创建tip,设置tip的位置 var _this=this; $("#tWarp").empty(); var _string=""+this.format(this.at['l'])+""+"@"+""+this.format(this.at['r'])+""; $("#tWarp").html(_string); var _left=$("#tWarp cite").offset().left+"px", _top=$("#tWarp cite").offset().top+parseInt($("#tWarp").css("line-height"))+"px"; if(parseInt(_top)>parseInt($("#tWarp").offset().top+$("#tWarp").height())) { _top=$("#tWarp").offset().top+$("#tWarp").height()+"px"; } $("#tipAt").css({ "left":_left, "top":_top, "display":"block" }); $("#tipAt li").eq(1).addClass("on").siblings().removeClass("on"); _this.hover(); //取消keyup绑定,绑定keydown,键盘操作选择,避免与文本框的事件冲突 $(_this.elem).unbind('keyup').bind('keydown', function(e) { return _this.keyMove(e); }); }, hiddenTip: function() { var _this=this; $("#tipAt").css("display","none"); $("#tipAt li").unbind("click,mouseover"); } }

然后我们添加键盘的操作,这里注意的是,我们在textarea输入文字的时候已经绑定keyup事件,为了避免事件多次绑定,tip的选择我们用keydown事件处理。

demonAt.prototype= { keyMove: function(e) {//键盘操作 var _this=this; var _key=e.keyCode; var _len=$("#tipAt li").length; switch(_key) { case 40: //下 _this.index++; if(_this.index>_len-1) { _this.index=1; } _this.keyMoveTo(_this.index); //return false一定要加上,不然JS会继续进行调用keyHandler,从而绑定了keyup事件影响到键盘的keydown事件 return false; break; case 38: //上 _this.index--; if(_this.index

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report