如何實現滑鼠放在圖片上出現文字說明效果?
阿新 • • 發佈:2019-01-26
最近在瀏覽網頁時,看到一些圖片,滑鼠一放上去呢,就會有說明文字“浮”上來,移開又“沉”下去,感覺好炫!自己就在網上找實現程式碼啊,看看事件是怎麼實現的!然後就找到了如下的程式碼:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.softwhy.com/" /> <title>螞蟻部落</title> <style type="text/css"> .main{ width:738px; height:280px; margin:0px auto; border:5px solid #696; position:relative; } a{text-decoration:none} .main .cite{ width:738px; position:absolute; bottom:0px; left:0px; text-align:center; -moz-opacity:0.5; filter:alpha(opacity=50); opacity:0.5; background:#333; border-bottom:2px solid #000; border-top:2px solid #000; color:white; overflow:hidden; display:none; } .main .word{ position:absolute; height:0px; width:738px; text-align:center; bottom:0px; left:0px; color:white; display:block; overflow:hidden; } </style> <script type="text/javascript"> var speed=10; var citeH=0; var flag; window.onload=function(){ var cite=document.getElementById("cite"); var word=document.getElementById("word"); var main=document.getElementById("main"); function addHeight(){ clearInterval(flag); cite.style.display="block"; if(citeH<86){ citeH=citeH+1; cite.style.height=citeH+"px"; word.style.height=citeH+"px"; } else{ clearInterval(flag); return; } flag=setInterval(addHeight,speed); } function reduceHeight(){ clearInterval(flag); if(citeH>0){ citeH=citeH-1; cite.style.height=citeH+"px"; word.style.height=citeH+"px"; } else{ clearInterval(flag); cite.style.display="none"; return; } flag=setInterval(reduceHeight,speed); } if(main.addEventListener){ main.addEventListener("mouseover",addHeight,false); main.addEventListener("mouseout",reduceHeight,false); } else{ main.attachEvent("onmouseover",addHeight); main.attachEvent("onmouseout",reduceHeight); } } </script> </head> <body> <div class="main" id="main"> <a href="#"> <img src="1.jpg" border="0"> <div class="cite" id="cite"></div> <div class="word" id="word">愛護大自然,共享自然風光</div> </a> </div> </body> </html>
恩呢,放在編譯器裡,的確有效果,的確是我想象中的那樣,可是,我自己感覺寫的太複雜了,挺簡單的一個問題對吧?然後就自己寫了,剛開始有點小問題,不知道怎麼實現那個上浮效果,最後想到了overflow這個屬性,寫出了以下程式碼:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="txex/html charset=utf-8" > <script src="jquery-1.11.1.js"></script> <style type="text/css"> body{ font-family: simhei; } p{ color: #ffffff; } div{ overflow: hidden; } </style> <script type="text/javascript"> $(document).ready(function(){ $(".pic").mouseover(function() { $(".he").animate({top:'280px'},500);}) $(".pic").mouseout(function() {$(".he").animate({top:'330px'},500);} ) }); </script> </head> <body> <div style="position: relative"> <img src="test.png" class="pic"> <div style="width:231px;height: 50px;background-color: orange;position: absolute;top:330px" class="he"> <p align="center" >開始答題</p> </div> </div> </body> </html>
是不是比上邊那個簡單多了,也很容易理解,實現了同樣的效果。所以總結了,寫程式碼也要講究簡單高效,是要靠“智商”去寫的,恩恩,問題本身還是比較簡單的,就是自己的“靈機一動”後,有點感概,與大家分享分享!