使用cookie和JavaScript的响应式图像

时间:2018-04-04 11:38:55

标签: javascript css responsive

我一直在读一本名为"由Benjamine Lagrone撰写的HTML5和CSS3响应式网页设计手册"在第8页。代码已经给出,但问题是指令对我来说不是很清楚。我曾经看到过类似于书的问题,链接是:

https://keithclark.co.uk/articles/responsive-images-using-cookies/

但是,说明也不清楚。它没有说我应该创建什么文件。所以我把所有代码都只用了2个文件和3个图像。我只知道javascript的基础知识,所以我在这里有点困惑。

这是我的代码 第一个文件:这位于图像文件夹之外。我把它命名为" index.html"

<!doctype html>
<html>
<head>
  <title>Responsive Images Test</title>
  <meta charset="utf-8">
  <script>
    document.cookie = "device_dimensions=" + screen.width + "x" + screen.height;
  </script>
</head>
<body>
  <img src="images/?test.png">
  <!-- the above is equivalent to: <img src="images/index.php?test.png"> -->
</body>
</html>

第二档:我把它命名为#34; index.php&#34;内部图像文件夹

<!doctype html>
<html>
<head>
  <title>Responsive Images Test</title>
  <meta charset="utf-8">
  <script>
    document.cookie = "device_dimensions=" + screen.width + "x" + screen.height;
  </script>
</head>
<body>


<?php
  $device_width = 0;
  $device_height = 0;
  $file = $_SERVER['QUERY_STRING'];

  if (file_exists($file)) {

    // Read the device viewport dimensions
    if (isset($_COOKIE['device_dimensions'])) {
      $dimensions = explode('x', $_COOKIE['device_dimensions']);
      if (count($dimensions) == 2) {
        $device_width = intval($dimensions[0]);
        $device_height = intval($dimensions[1]);
      }
    }

    if ($device_width > 0) {

      $fileext = pathinfo($file, PATHINFO_EXTENSION);

      // Low resolution image
      if ($device_width <= 800) {
        $output_file = substr_replace($file, '-low', -strlen($fileext) - 1, 0);
      } 

      // Medium resolution image
      else if ($device_width <= 1024) {
        $output_file = substr_replace($file, '-med', -strlen($fileext) - 1, 0);
      }

      // check the file exists
      if (isset($output_file) && file_exists($output_file)) {
        $file = $output_file;
      }
    }

    // return the file;
    readfile($file);
  }
?>

</body>
</html>

我该怎么办?在浏览器中看不到图像以显示它的响应。

1 个答案:

答案 0 :(得分:1)

PHP需要:

  1. 为您要加载的图片输出正确的内容类型标题(例如header("Content-Type: image/png")
  2. 仅输出HTTP标头和图像。您必须删除所有HTML(将被视为损坏的图像数据)。