function getDOM(id){ return document.getElementById(id); } function addEvent(id,event,fn){ var el = getDOM(id) || document; if(el.addEventListener){ el.addEventListener(event,fn,false); }else if(el.attachEvent){ el.attachEvent('on'+event,fn); } } function getElementLeft(element){ var actualLeft = element.offsetLeft; var current = element.offsetParent; while (current !== null){ actualLeft += current.offsetLeft; current = current.offsetParent; } return actualLeft; } function getElementTop(element){ var actualTop = element.offsetTop; var current = element.offsetParent; while(current !== null){ actualTop += current.offsetTop; current = current.offsetParent; } return actualTop; } function ajaxGet(){ var xhr = null; if(window.XMLHttpRequest){ xhr = new window.XMLHttpRequest(); }else if(window.ActiveXObject){ xhr = new ActiveXObject("Msxml2.HMLHTTP"); } xhr.onreadystatechange = function(){ if(xhr.readyState ==4 && xhr.status ==200){ callback(JSON.parse(xhr.responseText)); } } xhr.open('get',url,true); xhr.send(null); } function delegateEvent(target,event,fn){ addEvent(document,event,function(e){ if(e.target.nodeName == target.toUpperCase()){ fn.call(e.target); } }); } addEvent('search-input','keyup',function(){ var searchText = getDOM('search-input').value; ajaxGet('http://api.bing.com/qsonhs.aspx?q='+searchText,function(d){ var d = d.AS.Results[0].Suggests; var html = ''; for (var i = 0;i<d.length;i++){ html += '<li>'+d[i].Txt+'</li>'; } getDOM('search-suggest').style.top = getElementTop(getDOM('search-form'))+38+'px'; getDOM('search-suggest').style.left = getElementLeft(getDOM('search-form'))+'px'; getDOM('search-suggest').style.position = 'absolute'; getDOM('search-suggest').style.display = 'block'; }); }); delegateEvent('li','click',function(){ var keyword = this.innerHTML; location.href = 'http://cn.bing.com/search?q='+keyword; });
串猪神
相关分类