JavaScript 数组中每个图像的路径名



我写了一个简单的代码来导航图像文件夹。它适用于网络漫画网站,因此每个图像单独显示,然后下一个和上一个按钮循环浏览可用内容。

我的问题是图像编号没有显示在URL中,因此您无法链接到单个漫画,这使得共享,RSS等相当无效。

我不知道我是否需要尝试使用 PHP 显示路径,或者是否可以将其作为变量添加到我现有的 Javascript 中,或者脚本是否需要嵌入到索引页本身中。我已经研究了几个小时,我认为location.path可能是关键,但我无法弄清楚如何成功实现它。

var images = ["comic_imgs/1.jpg",
    "comic_imgs/2.jpg",
    "comic_imgs/3.jpg",
    "comic_imgs/4.jpg",
    "comic_imgs/5.jpg",
];
var index = 4;
function nextImage()
{
    ++index;
    if (index < images.length)
    {
        document.getElementById("ID").setAttribute("src", images[index]);
    }
    else
    {
        index = (images.length - 1);
        nextImage();
    }
}
function previousImage()
{
    --index;
    if (index > -1)
    {
        document.getElementById("ID").setAttribute("src", images[index]);
    }
    else
    {
        index = 1;
        previousImage();
    }
}
function firstImage()
{
    index = 0;
    document.getElementById("ID").setAttribute("src", images[index]);
}
function lastImage()
{
    index = (images.length - 1);
    document.getElementById("ID").setAttribute("src", images[index]);
}

感谢您的观看!

您正在做的是更改 #ID 元素的 src。

例如,如果这是您的 HTML:

<img src='[url]' id='ID'/>

您可以使用 A 标签封装您的 img,因为这将允许用户获得指向给定图像的链接:

<a href='[url]'><img src='[url]' id='ID'/></a>

然后(要在更改 src 时更改 href),您只需要添加:

document.getElementById("ID").parentNode.setAttribute("href", images[index]);你正在做的任何地方document.getElementById("ID").setAttribute("src", images[index]);

最新更新