toggle image on hover using Jquery

北慕城南 提交于 2019-12-31 04:17:30

问题


First of all please dont suggest me to do this using css.

I need to toggle between two images on-hover using Jquery. I need that two images (two toggling images) should be downloaded at the time of page load. Cause else it will create a lag time for the first time. As my images are two banners on the home page.I need to do something creating a image object , thus pre-loading it and later on toggling the objects.

I cant do this using simple css cause there will be a lag for the first time user as the image is not present on page load. and it gives a bad look.


回答1:


$(function(){
   var imgs = [
       new Image(),
       new Image()
   ];

   imgs[0].src = 'http://www.typeofnan.com/pic1.jpg';
   imgs[1].src = 'http://www.typeofnan.com/pic2.jpg';

   $('#hoverelement').hover(function(){
      $(this).html(imgs[0]);
   }, function(){
      $(this).html(imgs[1]);
   });
});​

That should work, even if I'm not sure if that is what you need. You can add an onload event to both images to makes sure, they are really loaded before allowing hovering.




回答2:


Here's the Quick Demo of below Code : http://jsbin.com/itunu

HTML :

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Hello world !!</title>

</head>
<body>
  <img  />
</body>
</html>

Javascript :

var a = [];

a[0] = "http://i577.photobucket.com/albums/ss219/music_munster/powerpuff-girls-092.jpg";
a[1] = "http://img.listal.com/image/459059/500full.jpg";


$(document).ready(function() {
  var source = $.preload(a); 
  $('img').attr('src',source[0].src); //just an acknowledgement (pre-loading done)
  $('img').hover(function() {
    $('img').attr('src',source[1].src);
  },function() {
    $('img').attr('src',source[0].src);    
  });

});



//Image Preloading....  
var cache = [];
  $.preload = function(arr) {
    for(var i = 0; i<arr.length; i++) {
      var img = new Image();
      img.src = arr[i];
      cache.push(img);
    }
    return cache;
  };


来源:https://stackoverflow.com/questions/3556856/toggle-image-on-hover-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!