简体   繁体   English

如何顺利改变 <img src=“…” /> 用jQuery?

[英]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 . 使用CSS精灵

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 使用CSS预加载图像

perload the image and put it in div that have a opacity:0;height:0;width:0; perload图像并将其放在具有不透明度的div中:0;高度:0;宽度:0;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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