如果可能的话,我真的可以在家庭作业上使用一些帮助。对于我当前的项目,我们的任务是在点击时从上面的列表中获取图像。字幕也应淡出并与图像一起显示。我有旧的图像和标题逐渐淡出,但无法弄清楚如何让新的图像和淡出淡出。代码如下:
$(document).ready(function() {
// preload images
$("#image_list a").each(function() {
var swappedImage = new Image();
swappedImage.src = $(this).attr("href");
});
// set up event handlers for links
$("#image_list a").click(function(evt) {
var imageURL = $(this).attr("href");
$("#image").fadeOut('slow', function() {
$("#image").load(function() {
$("#image").fadeIn();
}).attr("src", imageURL);
});
var caption = $(this).attr("title");
$("#caption").fadeOut('slow', function() {
$("#caption").load(function() {
$("#caption").fadeIn();
}).text(caption);
});
// cancel the default action of the link
evt.preventDefault();
}); // end click
// move focus to first thumbnail
$("li:first-child a").focus();
}); // end ready
你可以在这种情况下抛弃.load()
,因为它似乎没有达到目的。它也从jQuery 3.0中删除。
我建议的另一件事是将重复查找存储为变量,而不是一遍又一遍地持续执行相同的DOM查找。
$(document).ready(function() {
var $image_list_a = $("#image_list_a");
// preload images
$image_list_a.each(function() {
var swappedImage = new Image();
swappedImage.src = $(this).attr("href");
});
// set up event handlers for links
$image_list_a.click(function(evt) {
var $image = $("#image");
var $caption = $("#caption");
var imageURL = $(this).attr("href");
$image.fadeOut('slow', function() {
$image.attr("src", imageURL).fadeIn();
});
var caption = $(this).attr("title");
$caption.fadeOut('slow', function() {
$caption.text(caption).fadeIn();
});
// cancel the default action of the link
evt.preventDefault();
}); // end click
// move focus to first thumbnail
$("li:first-child a").focus();
}); // end ready