← Назад в «Блог»
35

Кнопка Play и Pause для тега video

Сделал кейс с кучей видео, смотрю его и думаю: «ну как же хреново, что кнопки управления видео внизу».

Пользователю из-за отсутствия других визуальных элементов нужно будет целиться в самый угол.

Нам нужно, чтобы кнопка плей была по центру, вот так.

Сходил в нейронку, попросил написать скрипт, чуть подправил и готово. Теперь есть удобная кнопка воспроизведения.

Код

Если будете вставлять в javascript файл, не забудьте убрать теги script.


(function () {
  // ===== стили =====
  var css = `
  .video-play-wrap {
    position: relative;
    display: inline-block;
    max-width: 100%;
  }
  .video-play-wrap video {
    display: block;
    width: 100%;
    height: auto;
  }
  .video-play-overlay {
    position: absolute;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    pointer-events: none;
  }
  .video-play-btn {
    width: 74px;
    height: 74px;
    border-radius: 9999px;
    background: rgba(0,0,0,0.55);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    pointer-events: auto;
    transition: transform .2s ease, opacity .2s ease;
  }
  /* PLAY */
  .video-play-btn[data-state="play"]::before {
    content: '';
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 14px 0 14px 20px;
    border-color: transparent transparent transparent #fff;
    margin-left: 4px; /* ← как просил */
  }
  /* PAUSE, полоски ближе */
  .video-play-btn[data-state="pause"]::before {
    content: '';
    display: block;
    width: 10px;
    height: 20px;
    border-left: 4px solid #fff;
    border-right: 4px solid #fff;
  }
  .video-play-btn.is-hidden {
    opacity: 0;
    pointer-events: none;
    transform: scale(.8);
  }
  `;
  var style = document.createElement('style');
  style.textContent = css;
  document.head.appendChild(style);

  // ===== логика =====
  var videos = document.querySelectorAll('video');

  videos.forEach(function (video) {
    if (video.closest('.video-play-wrap')) return;

    var wrap = document.createElement('div');
    wrap.className = 'video-play-wrap';
    video.parentNode.insertBefore(wrap, video);
    wrap.appendChild(video);

    var overlay = document.createElement('div');
    overlay.className = 'video-play-overlay';

    var btn = document.createElement('div');
    btn.className = 'video-play-btn';
    btn.setAttribute('data-state', 'play');
    overlay.appendChild(btn);
    wrap.appendChild(overlay);

    var hideTimer = null;

    function showBtn(state) {
      if (state) btn.setAttribute('data-state', state);
      btn.classList.remove('is-hidden');
    }
    function hideBtn() {
      btn.classList.add('is-hidden');
    }
    function enableControlsIfNeeded() {
      if (!video.hasAttribute('controls')) {
        video.setAttribute('controls', '');
      }
    }

    // клик по кнопке
    btn.addEventListener('click', function (e) {
      e.stopPropagation();
      var state = btn.getAttribute('data-state');
      if (state === 'play') {
        enableControlsIfNeeded();
        video.play();
      } else {
        video.pause();
      }
    });

    // клик по видео
    video.addEventListener('click', function () {
      if (video.paused) {
        enableControlsIfNeeded();
        video.play();
      } else {
        video.pause();
      }
    });

    // события видео
    video.addEventListener('play', function () {
      hideBtn();
    });

    video.addEventListener('pause', function () {
      clearTimeout(hideTimer);
      showBtn('play');
    });

    video.addEventListener('ended', function () {
      clearTimeout(hideTimer);
      showBtn('play');
    });

    // показ паузы при движении
    function userMoved() {
      if (!video.paused) {
        showBtn('pause');
        clearTimeout(hideTimer);
        hideTimer = setTimeout(function () {
          if (!video.paused) {
            hideBtn();
          }
        }, 2000);
      }
    }

    // мышь/тач
    wrap.addEventListener('mousemove', userMoved);
    wrap.addEventListener('touchstart', userMoved, {passive: true});

    // если курсор ушёл с видео и оно играет — сразу спрятать
    wrap.addEventListener('mouseleave', function () {
      if (!video.paused) {
        clearTimeout(hideTimer);
        hideBtn();
      }
    });

    // старт
    showBtn('play');
  });
})();
Полезно
1
Непонятно
Поделиться
Отправить
Линкануть
Вотсапнуть

Канал Дани в телеграме

В канале показываю, как разрабатываю продукты: нейронки, боты, пет-проекты, бизнес. Делюсь фишками о разработке и дизайне. Без рекламы.

Подписаться
← Назад в «Блог»

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Контакты