简体   繁体   中英

How to smoothly change <img src=“…” /> with jQuery?

I'm now doing something like :

$img.hover(function(){$(this).attr('src','1.jpg')},function(){$(this).attr('src','2.jpg')});

Which is not smooth,because it takes quite some time to load an image.

What about pre-loading your images when the page loads:

$(function () {
  var preloadImages = ['1.jpg', '2.jpg'];

  $.each(preloadImages, function () {
    $('<img/>').attr('src', this);
  });

  // ...
});

Change that to a background image with both the images combined and change the background position dynamically.

Use CSS sprites .

If you need to stick with an image itself then preload the two images and then it will take the second image from the cache which won't cause the delay.

Preloading Images With CSS

perload the image and put it in div that have a opacity:0;height:0;width:0;

preload_url = $(this).data('hover_image');
$('body').append('<div style="opacity:0;height:0;width:0"><img src="'+preload_url+'"></div>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM