褪色改变背景图像

我有一个脚本,根据我滚动的位置在背景图像之间切换。 我能够正确地切换背景图像,但是我要求我有背景图像fadeIn()而不是简单地改变。 基本上,我循环遍历背景图像,我希望前一个fadeOut()和下一个fadeIn() 。 是否有可能做到这一点? 如果是这样,怎么样? 这是脚本。

 $("#scroll").on("slidestart", function(ev, ui){ $(this).on("mousemove touchmove", function(){ var slider_pos = $("span").offset().top; $("#menu").find(".schematics").each(function(ev){ var schematic_id = $(this).data("id").split("_")[0]; var schematic_top = $(this).offset().top; var schematic_height = $(this).height(); var schematic_bottom = (schematic_top + schematic_height); var url = $(this).data("url"); 

这是背景图像变化的地方。 我认为在css操作可以工作之后添加fadeIn() ,但事实并非如此。

  if((slider_pos >= schematic_top) && (slider_pos <= schematic_bottom)){ $("#plane_image").css("background-image", "url(" +url +")").fadeIn("slow"); $(".vis").hide(); $(".title").hide(); $("#" +schematic_id +"_list").show(); $("#" +schematic_id +"_head").show(); } }) }) }) 

jQuery的fadeIn和fadeOut函数有一个“完整”函数,在动画完成后调用。 你可以尝试这样的事情。

 var slideTimeout; // global var for any slider timeout if((slider_pos >= schematic_top) && (slider_pos <= schematic_bottom)){ if(slideTimeout) { clearTimeout(slideTimeout); // clears the timeout if we detect a new slide movement. } slideTimeout = setTimeout(function(){ $("#plane_image").fadeOut("slow", function(){ $("#plane_image").css("background-image", "url(" +url +")").fadeIn("slow", function(){ $(".vis").hide(); $(".title").hide(); $("#" +schematic_id +"_list").show(); $("#" +schematic_id +"_head").show(); }); }); }, 1000); // it will wait 1 second before firing the method again } 

或者你可以用布尔方式做到这一点。

 var inVisibleRegion = false; if((slider_pos >= schematic_top) && (slider_pos <= schematic_bottom)){ if(!inVisibleRegion) { $("#plane_image").fadeOut("slow", function(){ $("#plane_image").css("background-image", "url(" +url +")").fadeIn("slow", function(){ $(".vis").hide(); $(".title").hide(); $("#" +schematic_id +"_list").show(); $("#" +schematic_id +"_head").show(); }); }); inVisibleRegion = true; } } else { inVisibleRegion = false; } 

有关进一步的见解,请查看jQuery fadeIn()和jQuery fadeOut() 。

启动一个fadeOut,然后加载新的img并调用fadeIn,它会在完成fadeOut时触发(bg =你的元素)

 bg.fadeOut('slow', function () { bg.load(function () {bg.fadeIn();}); bg.attr("src", newbgdrc); });