【问题标题】:Why are images broken when viewed from sub directories?为什么从子目录查看图像会损坏?
【发布时间】:2014-02-11 19:38:02
【问题描述】:

编辑:你可以在这里看到我的意思:Test Page

页面上的图像是不相关的。它们一直工作到移动到 /test/n/ 或更深。 页面源显示正确链接的图像(非相对,正确的路径),但查看它们、复制它们的 url 并使用内联编辑器检查它们会将 url 显示为相对并破坏它。

例如,假设我使用路径 http://url.com/images/image.jpg - 如果我从 http://www.url.com/n/x/y/ 查看它 查看源代码时路径保持不变,但在其他地方显示为 /images/image.jpg 或 http://www.url.com/n/x/y/images.jpg

我发现它更令人困惑,因为链接的样式表和超链接仍然可以按预期工作。

我的测试文件夹中有以下 .htaccess 文件

RewriteEngine on
RewriteBase /test/
#
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
#
# Rewrite /test/n/x/y-p/
RewriteRule ^([^/]+)/([^/]+)/([^/]+)-([0-9]+)/$ index.php?n=$1&x=$2&y=$3&p=$4 [L,NC,QSA]
#
# Rewrite /test/n/x/y/
RewriteRule ^([^/]+)/([^/]+)/([^/]*)/$ index.php?n=$1&x=$2&y=$3 [L,NC,QSA]
#
# Rewrite /test/n/x-p/
RewriteRule ^([^/]+)/([^/]+)-([0-9]+)/$ index.php?n=$1&x=$2&p=$3 [L,NC,QSA]
#
# Rewrite /test/n/x/
RewriteRule ^([^/]+)/([^/]*)/$ index.php?n=$1&x=$2 [L,NC,QSA]
#
# Rewrite /test/n-p/
RewriteRule ^([^/]+)-([0-9]+)/$ index.php?n=$1&p=$2 [L,NC,QSA]
#
# Rewrite /test/n/
RewriteRule ^([-_a-zA-Z-]*)/?$ index.php?n=$1 [L,NC,QSA]

【问题讨论】:

    标签: html image apache .htaccess mod-rewrite


    【解决方案1】:

    似乎有些事情让您认为这是服务器端问题。但是不,它与 Apache、.htaccess 和 mod-rewrite 无关。

    其实问题是由这段 JavaScript 代码引起的:

    function eventSize(){
      if (window.innerWidth < 950)
      {
        document.getElementById('logo').src="template/images/logo_small.png";
      }
      if(window.innerWidth >= 950)
      {
        document.getElementById('logo').src="template/images/logo.png";
      }
    }
    $(document).ready(eventSize);
    $(window).resize(eventSize);
    

    它将您的 URL http://darksociety.org/test/template/images/logo.png 替换为 template/images/logo_small.pngtemplate/images/logo.png。但这些新 URL 并不总是有效。

    要解决这个问题,您可以删除该代码、修复其 URL 或使用正则表达式以获得更大的灵活性。

    例如:

    var img = document.getElementById('logo');
    img.src = window.innerWidth < 950
        ? img.src.replace(/^(.+)(\..+)$/, '$1_small$2')
        : img.src.replace(/^(.+)_small(\..+)$/, '$1$2');
    

    如果宽度小于 950 像素,上面的代码将在扩展点之前添加_small,否则将其删除:

    "http://darksociety.org/test/template/images/logo.png".replace(/^(.+)(\..+)$/, '$1_small$2');
        // "http://darksociety.org/test/template/images/logo_small.png"
    "http://darksociety.org/test/template/images/logo_small.png".replace(/^(.+)_small(\..+)$/, '$1$2');
        // "http://darksociety.org/test/template/images/logo.png"
    

    这样,即使您在 HTML 中更改了图片的 URL,也不需要更新 JavaScript 代码。

    【讨论】:

      猜你喜欢
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多