无法用JavaScript替换/使用relativie图像url.绝对路径有效,相对路径无效

Unable to replace/use relatvie image url with JavaScript. Absolute path works, relative does not

本文关键字:路径 有效 无效 相对 url 图像 JavaScript 替换 relativie 使用      更新时间:2023-09-26

我添加了我认为重要的部分。基本上,我的所有文件目前都在一个目录中。CSS使用相对路径在div#幻灯片上放置背景图像。然后,使用javascript和数组,我想更改背景图像。然而,js只有在我输入到图像的绝对路径时才有效

小提琴不会显示图像,但结构是存在的。通常,我有一个函数可以递增I并显示相应的图片,但我认为这对故障排除没有必要。

我尝试使用相对路径的原因是,我可能需要能够复制和粘贴整个文件夹,或者从没有互联网接入的电脑上的usb驱动器使用它。

在开发控制台中,当我设置I=1并运行该函数时,背景是空白的。当我设置了绝对路径并做同样的事情时,它会根据i值显示正确的图片。

谢谢你的帮助!

EDIT:当我将所有代码组合到html文档中时,所有内容都使用相对路径。因此,在使用不同的html/css/js文件编写路径时,我一定缺少一些简单的东西。

http://jsfiddle.net/xvs8ogjg/4/

HTML

<div id="slides"></div>

CSS

/* I'm using % based sizes on the actual version, but everything else is the same. */
#slides {
    width: 200px;
    height: 200px;
    margin: 0;
    /* this css loads the first image properly when the page loads */
    background-image: url("test1.svg");
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

JS-

//Array with images.  Images, css, and js are all in the same folder called slideshow for now.
var slides = document.getElementById('slides');
//Does not work
var images = new Array (
    "test1.svg",
    "test2.svg"
);
//Does not work, i thought i could trick it or something, idk
var images = new Array (
    "../slideshow/test1.svg",
    "../slideshow/test2.svg"
);
//Works
var images = new Array (
    "http://example.com/directory/slideshow/test1.svg",
    "http://example.com/directory/slideshow/test2.svg"
);
//Also works, locally
var images = new Array (
    "file:///C:/Users/myname/directory/slideshow/test1.svg",
    "file:///C:/Users/myname/directory/slideshow/test2.svg"
);
var i = 0;
var change = function() {
slides.style.backgroundImage = 'url("' + images[i] + '")';
};

这完全取决于您请求文件的位置。也没有办法从plunker中看到你在描述什么,因为这将是相对于plunker url的。

//Does not work, i thought i could trick it or something, idk
var images = new Array (
    "/directory/slideshow/test1.svg",
    "/directory/slideshow/test2.svg"
);

应在域上的任何位置工作。我通常避免在url中使用../