2013-08-26 115 views
0

我試圖通過將鼠標移到另一圖像上來更改我的div內部的圖像。但是,當我將鼠標移過時,我無法插入第二張圖像,而當我離開鼠標時,我無法將第一張圖像帶回。用jquery更改圖像背景

HTML

<head> 
    <link rel="stylesheet" href="TEST.css"/> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script> 
     $(document).ready(function(){ 
      $('img').mouseenter(function(){ 
       $(this).remove(); 
       $(this).css("background-image",  "url(http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png)"); 
      }); 
      $('img').mouseleave(function(){ 

      }); 
     }); 
    </script> 
</head> 

<body> 

    <div> 
     <img src="http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png"/> 
    </div> 

</body> 

回答

0

$.remove硬是將刪除頁面(不要刪除樣式)的元素。如果刪除它,則可以添加背景圖像。然後將其設置爲空字符串以將其刪除。

CodePen

$(document).ready(function(){ 
    $('img').mouseenter(function(){ 
    $(this).css("background-image",  "url(http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png)"); 
    }); 
    $('img').mouseleave(function(){ 
    $(this).css("background-image", ""); 
    }); 
}); 
3

DEMO

有了這個:

<img class="hoverable" src="image.png"/> 

你可以使用:

jQuery(function($){ // DOM Ready shorthand 

    var orgSrc; 
    $('.hoverable').hover(function(){  
     orgSrc = this.src;  
     this.src = "image2.png"; 
    }, function(){ 
     this.src = orgSrc;  
    }); 

}); 

使用data-*屬性:DEMO

$('.hoverable').hover(function(){  
    $(this).data('src', this.src);  
    this.src = "image2.png"; 
}, function(){ 
    this.src = $(this).data('src'); 
}); 

使用方法前,務必在jQuery API Docs仔細一看,獲得與方法和選擇的名字友好。另外我建議你打印jQuery Cheat Sheet,它總是好的有一個靠近辦公桌:)

+1

大加讚賞 –

-2
$(document).ready(function(){ 
     $(".hoverable").hover(
     function() { 
     $(this).attr("src","http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png"); 
     }, 
     function() { 
     $(this).attr("src","http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png"); 
     } 
    ); 
    }); 
+0

這些誰downvoted我的回答,您可以請註明爲downvotes的原因。 – Sasidharan

1

您還可以通過CSS只有做到這一點:

div:after{ 
    content: url('http://www.clker.com/cliparts/3/7/d/5/1197103862376117882Gioppino_Soccer_Ball.svg.med.png'); 
} 

div:hover:after{ 
    content: url('http://www.clker.com/cliparts/d/1/4/6/11971185311926706097Gioppino_Basketball.svg.med.png'); 
} 

演示http://codepen.io/anon/pen/ijeEq

+1

如果你使用精靈,它會更好。在你的例子中,需要一些時間來加載懸停的圖像... – Webberig

0

您不能將'background'屬性應用於圖像本身,所以從字面上看,您的代碼將無法工作(據我所知)。正如我所看到的,你是在一個div結束了你的形象,所以可能是你可以改變它是這樣的:

$('div img').mouseenter(function() 
{ 
$(this).attr('src','source_of_new_image'); 
}).mouseleave(function() 
{ 
$(this).attr('src','source_of_old_image'); 
});