jQuery动态图像加载

**当我在输入中键入引用时,我尝试加载图像。

     $(document).ready(function () { $('#id').focus(); $('#id').keyup(function () { $('#img').html(''); $('#img').hide().fadeIn('slow'); }); });     

fadeIn()不起作用,除非图像已经在缓存中。 我怎样才能每次都有淡入淡出? 提前完成。

编辑

另一个脚本,它的作品!

      $(document).ready(function () { $('#id').focus(); $('#id').keyup(function () { $('#img').attr('src', 'http://www.site.com/' + $(this).val() + '.jpg'); $('#img').hide(); }); $('#img').load(function () { $('#img').fadeIn('slow'); }); });     

您应该继续并缓存图像(将其预加载到变量中),以便您可以快速访问它。 您还可能希望使用jQuery的load()函数来告诉您何时加载了图像。 这是一个简单的例子:

 var theCachedImage = new Image(); /* Boolean that tells us whether or not the image has finished loading. */ var theBoolean; $(theCachedImage).load(function () { In this callback, the image has finished loading.Set "theBoolean" to true. theBoolean = true; }); theCachedImage.src = "your/image/source"; 

就像凯文提到的那样,fadeIn正在发挥作用。 什么都没有消失。

编辑:

keyUp函数中,只需检查条件布尔值,并相应地执行操作。 例:

 $('#id').keyup(function () { if (theBoolean) { $('#img').html(''); $('#img').hide().fadeIn('slow'); } else { /* Your image hasn't been loaded yet. Do something to let the user know * or figure out the appropriate action to take. */ } });