鼠标移到图片变化的三种写法(可移植性强、代码少)
當鼠標移動到某個圖片的時候,圖片變化。當鼠標移出去的時候,圖片變回來。下面是三種寫法:
第一種,也是最笨,最麻煩的寫法,如下:
1 $(".web-footer2 .inner").each(function(){
2 $(this).find("ul").eq(1).find("img").eq(0).hover(function(){
3 $(this).attr("src","/img/footer-qq2.png");
4 },function(){
5 $(this).attr("src","/img/footer-qq.png");
6 })
7 $(this).find("ul").eq(1).find("img").eq(1).hover(function(){
8 $(this).attr("src","/img/footer-weibo2.png");
9 },function(){
10 $(this).attr("src","/img/footer-weibo.png");
11 })
12 $(this).find("ul").eq(1).find("img").eq(2).hover(function(){
13 $(this).attr("src","/img/footer-qqweibo2.png");
14 },function(){
15 $(this).attr("src","/img/footer-qqweibo.png");
16 })
17 $(this).find("ul").eq(1).find("img").eq(3).hover(function(){
18 $(this).attr("src","/img/footer-weixin2.png");
19 },function(){
20 $(this).attr("src","/img/footer-weixin.png");
21 })
22 })
用了each、find、eq、hover。代碼重復、臃腫。而且可移植性特別差。下面是第二種
1 $(".web-footer2 .inner").on("mouseover mouseout","ul:eq(1) img",function(e){
2 if(e.type=="mouseover"){
3 if($(this).attr("src") == "/img/footer-qq.png"){
4 $(this).attr("src","/img/footer-qq2.png")
5 }else if(....){....}
6 }else if(e.type=="mouseout"){
7 if($(this).attr("src") == "/img/footer-qq2.png"){
8 $(this).attr("src","/img/footer-qq.png")
9 }else if(....){....}
10 }
11 })
用了on、attr函數,雖然代碼量減少,但可移植性還是特別的差。那么就有了第三種
1 $(".web-footer2 .inner").on("mouseover mouseout","ul:eq(1) img",function(e){
2 var img_arr = [
3 ["/img/footer-qq.png","/img/footer-qq2.png"],
4 ["/img/footer-weibo.png","/img/footer-weibo2.png"],
5 ["/img/footer-qqweibo.png","/img/footer-qqweibo2.png"],
6 ["/img/footer-weixin.png","/img/footer-weixin2.png"]
7 ];
8 var img_src = $(this).attr("src");
9 if(event.type=="mouseover"){
10 for(i=0;i<4;i++){
11 if($.inArray(img_src,img_arr[i]) !== -1){
12 if(img_src == img_arr[i][0]){
13 $(this).attr("src",img_arr[i][1]);
14 }
15 }
16 }
17 }else if(event.type=="mouseout"){
18 for(i=0;i<4;i++){
19 if($.inArray(img_src,img_arr[i]) !== -1){
20 if(img_src == img_arr[i][1]){
21 $(this).attr("src",img_arr[i][0]);
22 }
23 }
24 }
25 }
26 })
現在我重點來說第三種,也就是這一種。先把圖片變化前的路徑和變化后的路徑放到二維數組里(img_arr變量),img_src其實可以不需要,我只是為了方便。然后用if判斷語句,判斷event.type是否mouseover,也就是是否移到圖片上,當移到圖片上的時候用for循環,不用for循環的話。你移到一個圖片上后,所有圖片都會變。因為有4張圖,所以i=0;i<4。如果你的圖片不確定有多少的話,你可以設置幾個變量,如下
var img_length = $(".web-footer2 .inner").find("img"); //某個元素里的圖片總數。
然后改下for循環語句為for(i=0;i<img_length.length;i++)就行了
然后再來一個if語句,判斷當前鼠標移到的圖片地址是否在img_arr二維數組里(如果不存在返回-1,如果存在返回在數組里的第幾個),如果存在,則再判斷,當前這個圖片地址是否在對應二維數組里的第一個數組里的值(這話比較難理解,就是img_arr里的"/img/footer-qq.png"、"/img/footer-weibo.png"、"/img/footer-qqweibo.png"、["/img/footer-weixin.png")如果是相對應,就把當前鼠標所在的圖片改成二維數組里的第二個數組里的值,也就是("/img/footer-qq2.png"、"/img/footer-weibo2.png"、"/img/footer-qqweibo2.png"、"/img/footer-weixin2.png")
總結
以上是生活随笔為你收集整理的鼠标移到图片变化的三种写法(可移植性强、代码少)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Gatling 条件判断
- 下一篇: 去中心化存储项目终极指南 | Filec