javascript - 如何防止在 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>
解决方案
您可以在页面加载时调用您的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>
推荐阅读
- nestjs - 拦截器没有捕捉到由 Nestjs 中的守卫引发的错误
- php - Codeigniter 到 Laravel 解码
- postgresql - PgAdmin 4:保存服务器连接详细信息
- java - 如何通过 Java(Android 应用程序)中的 POST 请求将音频文件发送到服务器?
- git - 我们可能需要 pre-commit 和 pre-push 钩子来整理我们的代码
- node.js - 我使用了正文解析器,但在使用 Postman(JSON 数据)使用 Post 时它返回 { }
- reactjs - 如何使用反应根据从第一个选择项目中的选择更新选择项目
- sql - 有效地在几个表中找到最后日期 - Teradata SQL
- c# - 下载 FTP 存档
- angular - 如何以编程方式选择或设置焦点到 AG Grid 中的特定行?