您实际上想要发生什么并不明显,但是如果所需的结果是当您单击任一链接时它会更改背景图像,并带有淡入淡出过渡,我认为最好通过更改类来完成的背景。我会像在这个分叉的小提琴中那样做:
http://jsfiddle.net/4JGmK/1/
改变CSS:
#background {
opacity: 0;
margin: 0;
padding: 0;
z-index: -1;
position: absolute;
width: 100%;
height: 100%;
}
.background1 {
background-image: url("http://www.noupe.com/wp-content/themes/noupe/images/noupe-404.png");
}
.background2 {
background-image: url("http://upload.wikimedia.org/wikipedia/commons/7/7b/Sdf_losc-benf_22.11.05_-_4.JPG");
}
改变了js:
$(document).ready(function () {
$("#deneme").click(function(){deneme('background1', 'background2')});
$("#deneme2").click(function(){deneme('background2', 'background1')});
});
function deneme(newclass, oldclass) {
if ($('#background').hasClass(oldclass)) {
//fade out the other background first then fade the right one in
$('#background').animate({
opacity: 0
}, 3000, function () {
$('#background').removeClass(oldclass).addClass(newclass).animate({
opacity: 1
}, 3000);
});
} else if($('#background').hasClass(newclass)) {
//already got this background, don't do anything
return false;
} else {
//doesn't have either at the moment, fade in the right background
$('#background').addClass(newclass).animate({
opacity: 1
}, 3000);
}
}
我重构的 deneme 函数仍然感觉有点笨拙,但至少它可以工作。