在此应用程序中,我将图像上传到本地上传文件夹中,在MySQL database
中,我存储图像的名称。如何显示从database
获取的图像数组中的一张图像?目前,我设法使用EJS
显示所有上传的图像。如何设置单个显示的图像“ src”每10秒左右更改一次?
<% for(i=0; i<images.length; i++) { %>
<img src="/uploads/<%= images[i].name %>" alt="">
<% }; %>
答案 0 :(得分:2)
我对EJS知之甚少,因此如果有任何语法错误,请在您结束时进行更改。首先为所有图像和相同的类名创建一个唯一的ID。
<% for(i=0; i<images.length; i++) { %>
<% if(i == 0) { %>
<img class="allImage" src="/uploads/<%= images[i].name %>" alt="" id="image_<%= i %>">
<% }; %>
<% if(i != 0) { %>
<img class="allImage" src="/uploads/<%= images[i].name %>" alt="" image_id="test<%= i %>" style="display:none;">
<% }; %>
<% }; %>
您可以使if-else条件,也可以在样式标记中使用if。
现在,您需要定义一个javascript全局变量。该变量的值从0开始。
var a = 0;
创建一个函数,每10秒调用一次
window.setInterval(function(){
myFuction();
}, 10000);
检查图像的长度,以便在最后一次显示图像时,我们可以从0开始。
myFuction(){
a = a + 1; // increment global variable to show next image
var length = $('.allImage').length;
if(length == a || length > a){
a = 0;
}
$('.allImage').hide(); // First hide all image with same class
$('#image_'+a).show(); // Show next image
}
希望这将帮助您获得输出。这在php中对我有用,所以我希望对您也有用。如果有语法错误,请在结尾处进行更改。谢谢
答案 1 :(得分:0)
我以前没有使用过EJS,但是我想使用setTimeout进行一些操作,因为您希望在粗糙的时间内更改图像。 这是一个示例:https://repl.it/@johnoro/Image-shuffling-example 如果您希望它无随机地循环,则只需要保留一个索引即可。 我继续并添加了一个无随机性的版本链接。由于EJS只是JavaScript,因此我认为应该很容易将其转换为您的目的。让我知道您是否需要更多帮助!
并且,为了展示代码而不必前往另一个站点:
// Selects the DOM node with the unique id, 'switch'.
const img = document.querySelector('#switch');
const images = [
"https://picsum.photos/350",
"https://picsum.photos/300?blur",
"https://picsum.photos/300?grayscale&blur=2"
];
function changeImage() {
// This'll give us a floating point number that's between 0 and the length of the images.
const rand = Math.random() * images.length;
// This'll give us an integer between 0 and the last index of our images.
const index = Math.floor(rand);
img.src = images[index];
// Notice that the function calls itself with our desired time, in this case 5000 milliseconds, or 5 seconds.
setTimeout(changeImage, 5000);
}
// We have to call it for the first change!
setTimeout(changeImage, 5000);