根据文件夹更改img SRC

change img src according to folder

本文关键字:img SRC 文件夹      更新时间:2023-09-26

我有一个主文件夹"main"。它有一个名为"test1.html"的页面。它还有images文件夹。图片文件夹中有图片"pic1.png"。

在"主"文件夹中还有一个名为"sub"的子文件夹,其中包含一个页面"test2.html"。

场景:我插入pic1.png在img标签通过jquery在两个页面(在根文件夹以及子文件夹)。我应该如何处理不同页面的src ?例如,

test1.html——images/pic1.png

test2.html——…/images/pic1.png

为什么不包括两个源的相对路径呢?

/images/pic1.png 

这是一个解释相对路径的好网站。

你可以使用regex检查位置,并在jQuery中使用attr函数应用src

(''+window.location).match(/http:'/'/[^'/]*'/*root'/?(.*)/)[1]

这将匹配url中根之后没有斜杠的所有内容。

如果在根目录下它将为空你可以在变量

中使用..
var path = (''+window.location).match(/http:'/'/[^'/]*'/*root'/?(.*)/)[1]
if (path) {
   var prefix = '';
   for (var i=path.match(/'//).length;i--;) {
       prefix += '../';
   }
   $('img').each(function() {
      var $this = $(this)
      $this.attr('src', prefix + $this.attr('src'));
   });
}

这将改变页面上图像的所有SRC属性