jQuery动态图像加载 [英] jQuery dynamic image loading
问题描述
**我在输入中键入引用时尝试加载图像.
**I try to load an image when I type a reference in an input.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#id').focus();
$('#id').keyup(function () {
$('#img').html('<img src="http://www.site.com/' + $(this).val() + '.jpg"
width="200px">');
$('#img').hide().fadeIn('slow');
});
});
</script>
</head>
<body>
<input type="text" size="7" maxlength="7" id="id">
<div id="img"></div>
</body>
</html>
除图像已在缓存中之外,fadeIn()均不起作用.每次如何进行淡入?提前感谢.
The fadeIn() doesn't work, except if the image is already in cache. How can I have a fadeIn each time? Thanx in advance.
编辑
另一个脚本,它起作用了!
Another script, it works!
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(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');
});
});
</script>
</head>
<body>
<input type="text" size="7" maxlength="7" id="id">
<br>
<img id="img" width="200px">
</body>
</html>
推荐答案
您应该继续缓存图像(将其预加载到变量中),以便可以快速访问它.您可能还想利用jQuery的 load()函数告诉您图像何时具有已加载.这是一个简单的示例:
You should go ahead and cache the image (pre-load it into a variable) so that you can access it quickly. You also might want to make use of jQuery's load() function to tell you when the image has been loaded. Here's a quick example:
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正在运行.没什么可淡入的.
Like Kevin mentioned, the fadeIn is working. There's just nothing to fade in.
在您的keyUp
函数中,只需检查条件布尔值并相应地执行操作.示例:
In your keyUp
function, simply check the value of the conditional boolean and perform actions accordingly. Example:
$('#id').keyup(function () {
if (theBoolean) {
$('#img').html('<img src="http://www.site.com/' + $(this).val() + '.jpg"
width="200px">');
$('#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. */
}
});
这篇关于jQuery动态图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!