воскресенье, 21 августа 2016 г.

Автоматическое масштабирование видео на веб странице

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

1. В промежутке тега <head> пихаем Jquery:

    <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    </head>


2. Где нибудь после тега <body> пихаем:

 <script type="application/javascript">
       
        // -- After the document is ready
$(function() {
  // Find all YouTube and Vimeo videos
  var $allVideos = $("iframe[src*='www.youtube.com'], iframe[src*='player.vimeo.com']");

  // Figure out and save aspect ratio for each video
  $allVideos.each(function() {
    $(this)
      .data('aspectRatio', this.height / this.width)
      // and remove the hard coded width/height
      .removeAttr('height')
      .removeAttr('width');
  });

  // When the window is resized
  $(window).resize(function() {
    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {
      var $el = $(this);
      // Get parent width of this video
      var newWidth = $el.parent().width();
      $el
        .width(newWidth)
        .height(newWidth * $el.data('aspectRatio'));
    });

  // Kick off one resize to fix all videos on page load
  }).resize();
});
        </script>
3. Ну и далее вставляем само видео:

<iframe src="https://www.youtube.com/embed/3YXaGCApK1w" width="560" height="314" allowfullscreen="allowfullscreen"></iframe>
P.S: Данный скрипт работает для Vimeo и Youtube. Если же надо для чего то другого, то его придётся допилить...

Комментариев нет:

Отправить комментарий