2015-10-22 5 views
-2

Я разрабатываю новую галерею фотографий для веб-сайта, и я считаю, галерея должна иметь некоторые способности, включая:Для петли и Lazyloader

  1. Использование Glob получить только JPG файлы в определенной папке
  2. Использование ленивым загрузчик для повышения производительности и скорости загрузки.

Первый бит - довольно простая задача для меня, но когда дело доходит до второй задачи, я быстро смущаюсь.

Поскольку первая функция будет полностью заполнять всю папку и отображать весь файл .jpg, который он содержит, я понятия не имею, как разбить цикл и возобновить его, когда пользователь хочет загрузить больше фотографий.

У меня есть свои коды, как это на данный момент:

<html> 
    <!--The concept on this widget is to : Check specific folder > Read & Loop thourght the whole folder > Output all the images contain > Lazy loader. 
    Therefore user only needs to drag the image in the file when adding new images.!--> 
    <head> 
     <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <!--prevent courrption in IE!--> 
    </head> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
    <link rel="stylesheet" type="text/css" href="styles.css" /> 
    <body> 

     <!--------------------Tradional selector!------------> 
     <!--<input type="file" id="files" name="files[]" multiple /> 
     <output id="list"></output>!--> 

     <!-------------------drag and drop!-----------------> 
     <div id="drop_zone">Drop files here</div> 
     <output id="list"></output> 

     <?php 
     foreach (glob("media/images/*.jpg") as $filename) { //glod to get .jpg files 
      echo "<img src='$filename' width=auto height='500'/> "; 
     } 
     ?> 



     <script> 
     // Check for the various File API support. 
     //validator 
     if (window.File && window.FileReader && window.FileList && window.Blob) { 
      // Great success! All the File APIs are supported. 
     // alert('working'); 
     } else { 
      //alert('The File APIs are not fully supported in this browser.'); 
     } 

     /*=======================standrad file selector==================== 

     function handleFileSelect(evt) { 
      var files = evt.target.files; // FileList object, MSDN standrad , a selector 

      // files is a FileList of File objects. List some properties. 
      var output = []; //This is an empty Array ! the result/output will be store in array 

      for (var i = 0, f; f = files[i]; i++) { 
      //The push() method adds new items to the end of an array, and returns the new length. 
      //example banana.push | banana is juz a var declare on top .push()is the method 
       output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', 
          f.size, ' bytes, last modified: ', 
          f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a', 
          '</li>'); 
      } 
      //path selector 
      document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>'; 
      } 

      document.getElementById('files').addEventListener('change', handleFileSelect, false); 

      */ 
     <!----------------------Drag and drop!---------------------------!> 
     function handleFileSelect(evt) { 
      event.stopPropagation(); <!--jquery libraries function > 
      event.preventDefault(); <!--This method does not accept any arguments. So when you drag the images it will do something else then the default action!--> 

      var files = evt.dataTransfer.files; // FileList object. 

      // files is a FileList of File objects. List some properties. 
      var output = [];//This is an empty Array ! the result/output will be store in array 

      for (var i = 0, f; f = files[i]; i++) { 
       output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ', 
          f.size, ' bytes, last modified: ', 
          f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a', 
          '</li>'); 
      } 
       //path selector 
      document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>'; 
      } 

      function handleDragOver(evt) { 
      evt.stopPropagation(); 
      evt.preventDefault(); 
      evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy. 

      // ^The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation. 

      /*There's few value rather than copy: 

      copy: A copy of the source item is made at the new location. 
      move: An item is moved to a new location. 
      link: A link is established to the source at the new location. 
      none: The item may not be dropped. 
      */ 
      } 

      // Setup the dnd listeners. 
      var dropZone = document.getElementById('drop_zone'); 
      dropZone.addEventListener('dragover', handleDragOver, false); 
      dropZone.addEventListener('drop', handleFileSelect, false); 
     </script> 
    </body> 
</html> 

Как я должен реализовать lazyloader в этой ситуации?

+1

Вы используете php для получения файлов, почему этот помеченный javascript/jquery? – Jamiec

+0

Потому что мой вопрос о LAZYLOADER плагин JQuery. Не понимаю, почему ненавистники прогоняют меня с неприемлемой причиной. – anson920520

+0

это действительно смутило меня с самого начала, я подумал, что вы говорили о ленивом загрузчике * шаблон дизайна * –

ответ

0

Ради обеспечения ответа, я предполагаю, что вы используете этот плагин: http://www.appelsiini.net/projects/lazyload

убедитесь, что ваши изображения имеют собственное имя класса, так что вы можете сказать Jquery LazyLoader какие изображения искать:

<?php 
     foreach (glob("media/images/*.jpg") as $filename) { //glod to get .jpg files 
      echo "<img class="lazyLoadMe" src='$filename' width=auto height='500'/> "; 
     } 
?> 

затем, в нижней части документа, добавьте следующее:

<script type="text/javascript" charset="utf-8"> 
    $(function() { 
     $("img.lazyLoadMe").lazyload(); 
    }); 
    </script> 

это приведет к тому, что lazyLoader будет работать с ленивыми изображениями только с классом "lazyLoadMe".

Вам необязательно останавливать цикл php, который записывает все теги img в документ, поскольку lazyLoader автоматически проверяет, не загружены ли изображения, пока они не будут прокручиваться в представлении.