本文實例講述了JS實現的模仿QQ頭像資料卡顯示與隱藏效果。分享給大家供大家參考,具體如下:
我們使用QQ時經常需要查看朋友的資料卡,當我們把鼠標移入頭像時,資料卡顯示,并且鼠標能在頭像與資料卡之間能隨意移動,當鼠標移出頭像或資料卡時,資料卡延時隱藏。
實質就是延時提示框問題!

首先寫好布局:
<style> div { float:left; margin:5px; } .head { width:50px;height:50px;background-color:pink; } .info { width:250px;height:200px;background-color:blue;display:none; }</style><div> <div class="head"></div> <div class="info"></div></div>其次js部分:
思路:
(1)鼠標移入頭像,資料卡顯示;鼠標移出頭像,資料卡延時隱藏setTimeout
(2)鼠標移入資料卡,資料卡仍顯示,并清除資料卡延時隱藏的變量
(3)鼠標移出資料卡,資料卡延時隱藏,并且此時如果在移入到頭像中,資料卡扔顯示,并清除資料卡延時隱藏的變量
window.onload =function(){ var oHead = document.getElementsByClassName("head")[0]; var oInfo = document.getElementsByClassName("info")[0]; var timer = null; oHead.onmouseover=function(){ clearTimeout(timer); oInfo.style.display="block"; }; oHead.onmouseout=function(){ timer = setTimeout(function(){ oInfo.style.display="none"; },500); }; oInfo.onmouseover=function(){ clearTimeout(timer); oInfo.style.display="block"; }; oInfo.onmouseout=function(){ timer = setTimeout(function(){ oInfo.style.display="none"; },500); };};優化代碼:
oInfo.onmouseover = oHead.onmouseover=function(){ clearTimeout(timer); oInfo.style.display="block";};oInfo.onmouseout = oHead.onmouseout=function(){ timer = setTimeout(function(){ oInfo.style.display="none"; },500);};函數封裝:
注意:事件 .xx 等于 [“xx”]
第一種:函數外獲取變量,調用函數,適用于一個或兩個元素調用此事件
window.onload =function(){ var oHead = document.getElementsByClassName("head")[0]; var oInfo = document.getElementsByClassName("info")[0]; reminder(oHead,oInfo,"onmouseover","onmouseout"); function reminder (div1,div2,event1,event2){ var timer = null; div1[event1] = div2[event1]=function(){ clearTimeout(timer); div2.style.display="block"; }; div1[event2] = div2[event2]=function(){ timer = setTimeout(function(){ div2.style.display="none"; },500); }; }};第二種:函數外獲取變量,調用函數,適用于多個元素調用此事件
window.onload =function(){ var number=0; reminder("head","info","onmouseover","onmouseout",number); function reminder (div1,div2,event1,event2,num){ var oHead = document.getElementsByClassName(div1)[num]; var oInfo = document.getElementsByClassName(div2)[num]; var timer = null; oHead[event1] = oInfo[event1]=function(){ clearTimeout(timer); oInfo.style.display="block"; }; oHead[event2] = oInfo[event2]=function(){ timer = setTimeout(function(){ oInfo.style.display="none"; },500); }; }};比如,一共有三個頭像的話,就可以用for循環遍歷為每個元素綁定事件:
var number=null;for(number=0;number<3;number++){ reminder("head","info","onmouseover","onmouseout",number);}更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答