首页 > 解决方案 > 如何防止在 Backstretch 中延迟显示第一张图像

问题描述

以下 Backstretch 脚本用于显示带有标题的渐变随机图像。但是,第一个图像和标题仅在页面加载后五秒延迟后出现,或者在“setInterval(loadRandomImage, 5000, images);”中设置的任何时间后出现。好像它是“setTimeout”。

请让我知道我做错了什么,或者应该添加以防止第一张图像显示延迟?

<script src="/js/jquery-1.7.2.min.js"></script>
  <script src="/js/jquery.backstretch.js"></script>  
  <script src="/js/jquery.backstretch.captionjs"></script>

<script>

// Preload
$(images).each(function(){
$("<img/>")[0].src = this.url;});

var images = new Array(); //array of imgs objects

images[0] = {url: "/images/backgrounds/l&h.jpg", caption: "Stan Laurel and Oliver Hardy"};
images[1] = {url: "/images/backgrounds/sherlock-watson.jpg", caption: "Basil Rathbone and Nigel Bruce"};
images[2] = {url: "/images/backgrounds/powell-loy.jpg", caption: "William Powell and Myrna Loy"};
images[3] = {url: "/images/backgrounds/conried-bergman-bogart.jpg", caption: "Paul Heinreid, Ingrid Bergman and Humphrey Bogart"};

function loadRandomImage(imgs) {
    var index = Math.floor(Math.random() * imgs.length);

    console.log("loadRandomImages(): index = "+ index);

    $.backstretch(imgs[index].url, {fade: 1500, speed: 5000}); 

    $("#caption").html(imgs[index].caption);
}

// Change images every 5 seconds
setInterval(loadRandomImage, 5000, images);

</script>


    <div id="caption"></div>

标签: javascript

解决方案


您可以在页面加载时调用您的loadRandomImage函数一次,然后让间隔完成其余的工作。

// Preload
$(images).each(function(){
$("<img/>")[0].src = this.url;});

var images = new Array(); //array of imgs objects

images[0] = {url: "/images/backgrounds/l&h.jpg", caption: "Stan Laurel and Oliver Hardy"};
images[1] = {url: "/images/backgrounds/sherlock-watson.jpg", caption: "Basil Rathbone and Nigel Bruce"};
images[2] = {url: "/images/backgrounds/powell-loy.jpg", caption: "William Powell and Myrna Loy"};
images[3] = {url: "/images/backgrounds/conried-bergman-bogart.jpg", caption: "Paul Heinreid, Ingrid Bergman and Humphrey Bogart"};

function loadRandomImage(imgs) {
    var index = Math.floor(Math.random() * imgs.length);

    console.log("loadRandomImages(): index = "+ index);

    $.backstretch(imgs[index].url, {fade: 1500, speed: 5000}); 

    $("#caption").html(imgs[index].caption);
}


// we run the function once at the beginning.
loadRandomImage(images);

// Change images every 5 seconds
setInterval(loadRandomImage, 5000, images);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
<div id="caption"></div>


推荐阅读