【问题标题】:How to display one image at the time from images array which are fetched from database?如何从数据库中获取的图像数组中同时显示一张图像?
【发布时间】:2019-10-09 22:14:48
【问题描述】:

在此应用程序中,我将图像上传到本地上传文件夹,并在MySQL database 中存储图像的名称。如何从database 获取的图像数组中同时显示一张图像?目前我设法使用EJS 显示所有上传的图像。如何设置单个显示的图像“src”每 10 秒左右更改一次?

<% for(i=0; i<images.length; i++) { %>
    <img src="/uploads/<%= images[i].name %>" alt="">
<% }; %>

【问题讨论】:

  • 您只想显示 1 张图片吗?第一个还是最后一个?
  • @Yogendra 我当时只想显示一张图片,但我想循环浏览所有图片
  • 我不了解 EJS,但我会尽力帮助您

标签: mysql node.js ejs


【解决方案1】:

我以前没有使用过 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);

【讨论】:

  • 现在看到另一个答案, setInterval 可能会更好,这样您就不必在函数中调用 setTimeout (尽管这是模拟的)。无论如何,我认为这种方式非常简单。
【解决方案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 inside style 标签。

现在您需要定义一个 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 中对我有用,所以我希望这也对你有用。如果有任何语法错误,请在最后进行更改。谢谢

【讨论】:

    猜你喜欢
    • 2021-04-13
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2011-10-28
    • 2013-03-26
    • 1970-01-01
    • 2018-11-08
    相关资源
    最近更新 更多