常常在網頁頁面上看到的一種效果-當滑鼠滑過(onmouseover)時,會變換成另一張圖片,這裡我們會利用字串(string)處理中的一個方法(replace)來製作。
首先,在此範例中,我將第一張圖命名為logo.png,將要替換的圖命名為logo-hover.png;再者,我使用了jQuery這個framework以迅速找到頁面的物件,所以在HTML中得先載入這隻js(可以先到jQuery官網下載min版本)。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-tw" lang="zh-tw"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>js string</title> <script src="script/jquery.js" type="text/javascript"></script> </head> …
接著寫入基本的html code。
HTML
<body> <ul class="gallery"> <li><a href="http://www.google.com.tw/" title="google search engine"><img src="images/logo.png" alt="logo" /></a></li> <li><a href="http://www.google.com.tw/" title="google search engine"><img src="images/logo.png" alt="logo" /></a></li> … <li><a href="http://www.google.com.tw/" title="google search engine"><img src="images/logo.png" alt="logo" /></a></li> </ul> </body> </html>
及簡單的css style(請參考以下code,不給予並不影響js運作)。
CSS
<style type="text/css">
body {
padding-top:4em
}
.gallery {
width:60%;
min-width:800px;
margin:auto;
padding:1em 0 2em;
border:4px dashed #666;
text-align:center;
list-style:none
}
.gallery li {
display:inline-block;
margin-top:1em;
vertical-align:top
}
.gallery img {
border:0;
vertical-align:bottom
}
</style>
以上只是準備工作而已,接下來才是這次主要js的內容。
Javascript
<script type="text/javascript">
$(document).ready(function(){
$("ul.gallery img").mouseover(function(){
var imgLink = $(this).attr("src");
imgLink = imgLink.replace(".png","-hover.png");
$(this).attr("src",imgLink);
});
$("ul.gallery img").mouseout(function(){
var imgLink = $(this).attr("src");
imgLink = imgLink.replace("-hover.png",".png");
$(this).attr("src",imgLink);
});
});
</script>
首先,$(document).ready(function(){})相當於js中的window.onload事件,$(“ul.gallery img”)是jQuery的selector用法,和css的selector差不多,意指找出ul且class名稱為gallery底下所有的img;接下來,依據滑鼠滑入滑出,所以我們必須分成上下二個事件,
- mouseover(滑入)
- 我命名了一im,gLink的變名,$(this)即取得我們滑過的該圖片,$(this).attr(“src”)即取得該圖片的路徑,之後將圖片的路徑傳給了imgLink。
- imgLink.replace(“.png”,”-hover.png”) 這裡用到了字串(string)處理中的replace(),若imgLink中有’.png’的字串,以’-hover.png’取代,這也就是為什麼在一開始要將圖片以此規則命名,若有需要請自行更改此命名,取代完之後再將值回傳給imgLink。
- 接著,再將值指定到圖片路徑。
- mouseout(滑出)
- 和mouseover沒有什麼太大的差異,重點在於replace()的地方將檔名再互換回來就可以了,所以就不再多述了。
底下提供了完整的code下載。
DOWNLOAD!








