您好,登錄后才能下訂單哦!
這篇文章主要介紹“用Javascript分析微博@功能”,在日常操作中,相信很多人在用Javascript分析微博@功能問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”用Javascript分析微博@功能”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
對這個功能進(jìn)行分析如下:
1、確定光標(biāo)的位置
2、textarea文本框里對字符串@的判斷
3、tip的彈出事件
4、鍵盤的操作事件
5、ajax調(diào)用
6、文字的插入
當(dāng)然還有其他的功能。
看著是不是感覺很復(fù)雜?沒關(guān)系,我們一步一步的分析。
首先我們要確定textarea的光標(biāo)位置。在W3C中,獲取光標(biāo)位置比較簡單,可以用selectionStart和selectionEnd,IE瀏覽器不支持這2個屬性 ,但是IE又一個document.selection對象,可以模擬實(shí)現(xiàn)相同的功能。代碼如下:
//先定義一個基本類,來設(shè)置一些全局變量 function demonAt(opts) { this.elem=opts.elem; //文本框 this.at= {}; //臨時保存文本框內(nèi)容截取屬性 this.opt= {}; this.searched=""; //用于判斷用戶輸入字符是否和前面一樣,如果一樣跳過ajax this.url=opts.url; this.index=1; } //微博的@功能 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;//光標(biāo)起始位置 rangeData.end=this.elem.selectionEnd;//光標(biāo)末尾位置 rangeData.text=this.elem.value.substring(0,this.elem.selectionStart);//獲取文本框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) {//設(shè)置光標(biāo) 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) {//插入文本參數(shù)操作的元素,數(shù)據(jù),起始坐標(biāo)位置,用戶輸入字符長度 //this.setCursor(this.elem,this.rangeData); this.elem.focus(); var _range; if(this.elem.setSelectionRange) {//W3C _tValue=this.elem.value;//獲取文本框內(nèi)容 var _start = nStart - nLen,//設(shè)置光標(biāo)起點(diǎn)光標(biāo)的位置-離@的文本長度 _end = _start + txtData.length,//設(shè)置光標(biāo)末尾,start+數(shù)據(jù)文字長度 _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);//移動光標(biāo) _range.text = txtData+" "; } } }
自定義一個rangeData對象,保存光標(biāo)的位置和textarea框內(nèi)從光標(biāo)位置到開始處的字符串;返回出來。這個對象在下面其他函數(shù)中會用到。根據(jù)光標(biāo)位置的確定,可以書寫文字插入函數(shù)add();有了上面的函數(shù),我們可以對textarea框內(nèi)@的字符判斷,然后實(shí)現(xiàn)tip層定位和彈出,如果判斷這個,我們可以用正則:
var _reg=/@[^@\s]{1,20}$/g;
那么定位呢,若在textarea內(nèi)判斷是不現(xiàn)實(shí)的,因?yàn)槲覀儫o法獲取正確的left和top值,所以這里需要模擬一個div層,將div插入到body 中,定位到與textarea相同的位置,然后獲取到textarea內(nèi)的文字,進(jìn)行字符串的拆分,加上標(biāo)簽元素,這樣可以獲取到正確的位置。說的有點(diǎn)繞了,看下面代碼能更直觀的表達(dá)。
var _string="<span>"+"@前面的文字"+"</span>"+"<cite>@</cite>"+"<span>"+"@后面的文字"+"</span>";
看到這句,很多人應(yīng)該理解做法,將這段append到上訴定位的div中,這樣,我們可以通過<cite>標(biāo)簽獲取到offset值了。于是我們寫下面的代碼:
demonAt.prototype= { init: function() {//首先我們要初始化 var _body=$("body"); var _div=$("<div id='tWarp'></div>"), _tip=$("<div id='tipAt'></div>"); _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字符內(nèi) var _string=""; if(_value.indexOf("@")>= 0&&_value.match(_reg)) { var _postion=_rangeData.start; var _oValue=_value.match(_reg)[0];//找到value中***匹配的數(shù)據(jù) var vReg=new RegExp("^"+_oValue+".*$","m");//跟數(shù)據(jù)匹配的正則 暫時保留 _value_value=_value.slice(0, _postion); //重寫_value 字符串截取 從0截取到光標(biāo)位置 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;//光標(biāo)位置 this.at['len']=_oValue.length;//光標(biāo)位置至@的長度,如 @頹廢小魔,即"頹廢小魔"的長度 this.showTip(this.url) } else {//alert(1) this.hiddenTip() } } else { this.hiddenTip() } }, buidTip: function() {//創(chuàng)建tip,設(shè)置tip的位置 var _this=this; $("#tWarp").empty(); var _string="<span>"+this.format(this.at['l'])+"</span>"+"<cite>@</cite>"+"<span>"+this.format(this.at['r'])+"</span>"; $("#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輸入文字的時候已經(jīng)綁定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會繼續(xù)進(jìn)行調(diào)用keyHandler,從而綁定了keyup事件影響到鍵盤的keydown事件 return false; break; case 38: //上 _this.index--; if(_this.index<1) { _this.index=_len-1; } _this.keyMoveTo(_this.index); return false; break; case 13: //enter鍵 var txtData=$(".on").text(); _this.add(_this.elem,txtData,_this.at['pos'],_this.at['len']) _this.keyHandler() return false; break; default: }; _this.keyHandler(); }, keyHandler: function() { var _this=this; _this.index=1; //enter鍵盤操作后重新綁定keyup $(_this.elem).unbind("keydown").bind("keyup", function() { _this.getAt(); }) }, keyMoveTo: function(index) { $("#tipAt li").removeClass("on").eq(index).addClass("on"); } }
然后添加tip的點(diǎn)擊事件和hover事件。
demonAt.prototype= { inset: function() {//給li綁定事件, var _this=this; $("#tipAt").delegate("li","click", function() {//事件委托 if($(this).index()==0) { _this.elem.focus(); return false; } else { var txtData=$(this).text(); _this.add(_this.elem,txtData,_this.at['pos'],_this.at['len']) _this.hiddenTip() } }) }, hover: function() { //hover事件 var _this=this; $("#tipAt li:not(:first)").hover( function() { _this.index=$(this).index(); $(this).addClass("hover").siblings().removeClass("on hover") }, function() { $(this).removeClass("hover"); }) } }
到此,關(guān)于“用Javascript分析微博@功能”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。