这里我使用的是jQuery 1.7.2,我试图动态加载GIF图像,并在加载GIF图像时显示加载动画。
这是我的HTML代码。目前,它显示了一个静态的JPG图像。在单击.image-button类时,我希望在GIF图像完全加载之前显示loading-animation,并在加载的gif显示时隐藏loading-animation div。如果用户再次单击.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的新手。我可以做一些小事情,比如点击隐藏/显示,但这超出了我的能力。有人能帮忙吗。
发布于 2014-09-16 07:45:02
试试这段代码,演示
$(".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();
};编辑
更新多个图像,演示
$(".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();
}
});https://stackoverflow.com/questions/25830680
复制相似问题