我在这里使用jQuery 1.7.2,我正在尝试动态加载GIF图像并在加载GIF图像时显示加载动画。
所以这是我的HTML代码。目前它显示静态JPG图像。点击.image-button
课程后,我希望显示loading-animation
,直到完全加载GIF图片并隐藏loading-animation
div作为加载的gif显示。如果用户再次点击链接.image-button
,我想要隐藏GIF图像并显示JPG。
<div class="image-container">
<a href="javascript:void(0);" class="image-button">
<div class="loading-animation hidden"></div>
<img class="gif-image hidden" src="http://www.example.com/images/empty.gif" gif-data="http://www.example.com/images/my-image.gif" />
<img class="jpg-image" src="http://www.example.com/images/my-image.jpg" />
</a>
</div>
我是复杂的jQuery东西的菜鸟。我可以点击隐藏/显示等小东西,但这超出了我的范围。有人可以帮忙。
答案 0 :(得分:1)
试试此代码Demo
$(".image-button").click(function () {
if ($(".jpg-image").is(":visible")) {
$(".loading-animation").show();
var gifImage = $(".gif-image").attr("gif-data");
$.loadImage(gifImage).done(function (image) {
$(".gif-image").attr("src", image.src).show();
$(".jpg-image").hide();
$(".loading-animation").hide();
});
} else {
$(".jpg-image").show();
$(".gif-image").hide();
}
});
loadImage
插件的代码
$.loadImage = function (url) {
// Define a "worker" function that should eventually resolve or reject the deferred object.
var loadImage = function (deferred) {
var image = new Image();
// Set up event handlers to know when the image has loaded
// or fails to load due to an error or abort.
image.onload = loaded;
image.onerror = errored; // URL returns 404, etc
image.onabort = errored; // IE may call this if user clicks "Stop"
// Setting the src property begins loading the image.
image.src = url;
function loaded() {
unbindEvents();
// Calling resolve means the image loaded sucessfully and is ready to use.
deferred.resolve(image);
}
function errored() {
unbindEvents();
// Calling reject means we failed to load the image (e.g. 404, server offline, etc).
deferred.reject(image);
}
function unbindEvents() {
// Ensures the event callbacks only get called once.
image.onload = null;
image.onerror = null;
image.onabort = null;
}
};
return $.Deferred(loadImage).promise();
};
修改强>
针对多张图片Demo
进行了更新$(".image-button").click(function () {
var $this = $(this);
if ($this.find(".jpg-image").is(":visible")) {
$this.find(".loading-animation").show();
var gifImage = $this.find(".gif-image").attr("gif-data");
$.loadImage(gifImage).done(function (image) {
$this.find(".gif-image").attr("src", image.src).show();
$this.find(".jpg-image").hide();
$this.find(".loading-animation").hide();
});
} else {
$this.find(".jpg-image").show();
$this.find(".gif-image").hide();
}
});