javascript - YouTube 视频在向下滚动或粘滞时静音但仍在播放

标签 javascript jquery video youtube-api youtube-javascript-api

如何创建 YouTube 视频,当标题上的内容在不显示或粘性向下滚动时发出声音和静音?

function onYouTubeIframeAPIReady() {

  $('iframe[src*="youtube"]').each(function(i) {
    var youtubeIframeId = $(this).attr('id');
    if (!youtubeIframeId) {
      youtubeIframeId = $(this).attr('src').split('?')[0].split('/').pop();
      $(this).attr('id', youtubeIframeId);
    }

    var $video = $("#" + youtubeIframeId),
      videoData = $video.data(),
      videoId = videoData.videoId;

    /**
     * Remove videoId property from data
     */

    //delete videoData.videoId;

    /* jshint camelcase:false */

    if ($(this).attr('src').indexOf('enablejsapi=1') > 0) {
      var player = new YT.Player(youtubeIframeId, {
        videoId: youtubeIframeId, // YouTube Video ID
        //videoId   : $video.data( "videoId" ), // YouTube Video ID
        // width        : "100%",                   // Player width (in px)
        // height       : "auto",                   // Player height (in px)
        playerVars: $.extend({
          autoplay: 1, // Auto-play the video on load
          controls: 1, // Show pause/play buttons in player
          showinfo: 0, // Hide the video title
          modestbranding: 1, // Hide the Youtube Logo
          loop: 1, // Run the video in a loop
          fs: 0, // Hide the full screen button
          cc_load_policy: 0, // Hide closed captions
          iv_load_policy: 3, // Hide the Video Annotations
          autohide: 0 // Hide video controls when playing
        }),

        // }, videoData ),
        events: {
          // onReady: function(e) {
          //   e.target.mute();
          // }
          onStateChange: onPlayerStateChange
        }
      });
    } else {

      $(this).attr('src', $(this).attr('src') + '&enablejsapi=1').on('load', function() {
        var player = new YT.Player(youtubeIframeId, {
          videoId: youtubeIframeId, // YouTube Video ID
          // videoId    : $video.data( "videoId" ), // YouTube Video ID
          // width      : "100%",                   // Player width (in px)
          // height         : "auto",                   // Player height (in px)
          playerVars: $.extend({
            autoplay: 1, // Auto-play the video on load
            controls: 1, // Show pause/play buttons in player
            showinfo: 0, // Hide the video title
            modestbranding: 1, // Hide the Youtube Logo
            loop: 1, // Run the video in a loop
            fs: 0, // Hide the full screen button
            cc_load_policy: 0, // Hide closed captions
            iv_load_policy: 3, // Hide the Video Annotations
            autohide: 0 // Hide video controls when playing
          }),

          // }, videoData ),
          events: {
            // onReady : function(e)
            // {
            //  var $video = $(e.target.a);
            //  if( $video.data( "mute" ) ) e.target.mute();
            //  else e.target.unMute();
            // },
            onStateChange: onPlayerStateChange
          }
        });
      });
    }
  });
  /* jshint camelcase:true */
}

这是我的滚动粘性视频

/**
 * FUNCTION STICKY YOUTUBE VIDEO ON SCROLL
 */

var $window = $(window),
  $stickyVideoContainer = $("#stickyvideo_container"),
  $btnHideStickyVideo = $("#hide_sticky_video"),
  $stickyVideo = $("#sticky_video"),
  $headerStickyVideo = $("#header_sticky_video");

function onPlayerStateChange(event) {
  var isPlay = 1 === event.data,
    isPause = 2 === event.data,
    isEnd = 0 === event.data;

  if (isPlay) {
    $stickyVideo.removeClass("is-paused");
    $stickyVideo.toggleClass("is-playing");
  }

  if (isPause) {
    $stickyVideo.removeClass("is-playing");
    $stickyVideo.toggleClass("is-paused");
  }

  if (isEnd) {
    $stickyVideo.removeClass("is-playing", "is-paused");
  }
}

function scrollVideoSticky($window, $stickyVideoContainer, $stickyVideo) {

  // var done = false;

  if ($stickyVideoContainer.length) {
    var containerTop = $stickyVideoContainer.offset().top,
      containerOffset = Math.floor(containerTop + ($stickyVideoContainer.outerHeight() / 2));

  }

  $window.on("resize", function() {
    if ($stickyVideoContainer.length) {
      containerTop = $stickyVideoContainer.offset().top,
        containerOffset = Math.floor(containerTop + ($stickyVideoContainer.outerHeight() / 2));
    }

  }).on("scroll", function() {

    if ($stickyVideo.hasClass('is-hide') && $btnHideStickyVideo.hasClass('is-hide') && $headerStickyVideo.hasClass('is-hide')) {
      if ($window.scrollTop() < containerOffset) {
        $btnHideStickyVideo.hide();
      } else {
        $btnHideStickyVideo.show();
      }

    } else {

      $stickyVideo.toggleClass("is-sticky", //&& $stickyVideo.hasClass( "is-playing" )
        $window.scrollTop() > containerOffset
      ).removeClass('is-show');

      $btnHideStickyVideo.toggleClass("is-sticky",
        $window.scrollTop() > containerOffset
      ).removeClass('is-show');

      $headerStickyVideo.toggleClass("is-sticky",
        $window.scrollTop() > containerOffset
      ).removeClass('is-show');
    }

  });
}

我希望标题上的视频发出声音,向下滚动时视频静音并仍在播放,并且当向后滚动到标题时,视频返回声音。

我已经把代码贴出来了

events: {
           onReady: function(e) {
             e.target.mute();
           }

在onYouTubeIframeAPIReady()中,视频都被静音,当我将该代码放入函数scrollVideoSticky()中时,粘性消失了。我应该将该代码放在哪里?

请帮助或分享您的想法,我们将不胜感激。谢谢!

最佳答案

我想出了一个脚本来处理来自 YT 视频和来自视频标签的视频的 N 个视频。如果视频正在播放但不在视口(viewport)中,它将变得粘滞。您可以引用我的代码在这里写下来

引用:https://codepen.io/aravi-pen/pen/VMaRvX

这里是JS

var ytIframeList, videoList, currentPlayer, closeButton, gradientOverlay, fullScreenIcon;

var inViewPortBol = true;

var ytIframeIdList = [];

var ytVideoId = [];

var ytPlayerId = [];

var videoTagId = [];

var events = new Array("ended", "pause", "playing");



document.addEventListener('DOMContentLoaded', function () {



    /*Adding Youtube Iframe API to body*/



    var youTubeVideoTag = document.createElement('script');

    youTubeVideoTag.src = "//www.youtube.com/iframe_api";

    var firstScriptTag = document.getElementsByTagName('script')[0];

    document.body.appendChild(youTubeVideoTag, firstScriptTag);



    /*Getting all the iframe from the Page and finding out valid URL and ID. Then creating instance of players*/



    ytIframeList = document.getElementsByTagName("iframe");

    for (i = 0; i < ytIframeList.length; i++) {

        if (new RegExp("\\b" + "enablejsapi" + "\\b").test(ytIframeList[i].src)) {

            var url = ytIframeList[i].src.replace(/(>|<)/gi, '').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);

            if (url[2] !== undefined) {

                ID = url[2].split(/[^0-9a-z_\-]/i);

                ID = ID[0];

                ytIframeIdList.push(ID);

                ytIframeList[i].id = "featured-video" + i;

                ytVideoId.push("ytVideoId" + i);

                ytVideoId[i] = document.getElementById(ytIframeList[i].id);

                ytPlayerId.push("player" + i);

            }

        }

    }



    /*Getting Video Tag List and Creating instances*/



    videoList = document.getElementsByTagName("video");

    for (i = 0; i < videoList.length; i++) {

        videoList[i].id = "video-featured" + i;

        videoTagId.push("videoPlayerId" + i);

        videoTagId[i] = document.getElementById(videoList[i].id);



    }

    for (i = 0; i < videoTagId.length; i++) {

        for (var j in events) {

            videoTagId[i].addEventListener(events[j], videoTagPlayerhandler, false);

        }

    }



    closeButton = document.querySelector("a.close-button");

    gradientOverlay = document.querySelector(".gradient-overlay");

    fullScreenIcon = document.querySelector("i.fa.fa-arrows-alt");

    fullScreenPlay();



});



window.onYouTubeIframeAPIReady = function () {

    for (i = 0; i < ytIframeIdList.length; i++) {

        ytPlayerId[i] = new YT.Player(ytIframeList[i].id, {

            events: {

                "onStateChange": onPlayerStateChange

            }

        });

    }

};



function videoTagPlayerhandler(e) {

    /*Play Rules*/

    for (i = 0; i < videoTagId.length; i++) {

        if (e.target == videoTagId[i]) {

            if (e.type == "playing") {

                currentPlayer = videoTagId[i];

                videoTagId[i].classList.remove("is-paused");

                videoTagId[i].classList.add("is-playing");

                break;

            }

        }

    }

    for (i = 0; i < videoTagId.length; i++) {

        if (currentPlayer == videoTagId[i]) {

            continue;

        }

        videoTagId[i].classList.remove("is-playing");

        videoTagId[i].classList.add("is-paused");

    }



    /*Pause Rules*/

    for (i = 0; i < videoTagId.length; i++) {

        if (e.target == videoTagId[i]) {

            if (e.type == "pause") {

                videoTagId[i].classList.add("is-paused");

                videoTagId[i].classList.remove("is-playing");

                videoTagId[i].pause();

            }

        }

    }



    /*Sticky Rules*/

    for (i = 0; i < videoTagId.length; i++) {

        if (videoTagId[i].classList.contains("is-sticky")) {

            videoTagId[i].pause();

            fullScreenIcon.style.display = "none";



        }

    }



    for (i = 0; i < ytPlayerId.length; i++) {

        if (ytVideoId[i].classList.contains("is-sticky")) {

            ytPlayerId[i].pauseVideo();

            fullScreenIcon.style.display = "none";



        }

    }


    /*End Rules*/

    for (i = 0; i < videoTagId.length; i++) {

        if (e.target == videoTagId[i]) {

            if (e.type == "ended") {

                videoTagId[i].classList.remove("is-playing");

                videoTagId[i].classList.remove("is-paused");

            }

        }

    }

    videohandler();

};



function onPlayerStateChange(event) {



    /*Play Rules*/



    for (i = 0; i < ytPlayerId.length; i++) {

        if (ytPlayerId[i].getPlayerState() === 1) {

            currentPlayer = ytVideoId[i];

            ytVideoId[i].classList.remove("is-paused");

            ytVideoId[i].classList.add("is-playing");

            break;

        }

    }

    for (i = 0; i < ytVideoId.length; i++) {

        if (currentPlayer == ytVideoId[i]) {

            continue;

        }

        ytVideoId[i].classList.remove("is-playing");

        ytVideoId[i].classList.add("is-paused");

    }



    /*Pause Rules*/



    for (i = 0; i < ytPlayerId.length; i++) {

        if (ytPlayerId[i].getPlayerState() === 2) {

            ytVideoId[i].classList.add("is-paused");

            ytVideoId[i].classList.remove("is-playing");

            ytPlayerId[i].pauseVideo();

        }

    }





    /*Sticky Rules*/



    for (i = 0; i < ytPlayerId.length; i++) {

        if (ytVideoId[i].classList.contains("is-sticky")) {

            ytPlayerId[i].pauseVideo();

            fullScreenIcon.style.display = "none";



        }

    }



    for (i = 0; i < videoTagId.length; i++) {

        if (videoTagId[i].classList.contains("is-sticky")) {

            videoTagId[i].pause();

            fullScreenIcon.style.display = "none";



        }

    }



    /*End Rule*/



    for (i = 0; i < ytPlayerId.length; i++) {

        if (ytPlayerId[i].getPlayerState() === 0) {

            ytVideoId[i].classList.remove("is-playing");

            ytVideoId[i].classList.remove("is-paused");

        }

    }

    videohandler();

}



function videohandler() {



    if (currentPlayer) {

        if (closeButton) {

            closeButton.addEventListener("click", function (e) {

                if (currentPlayer.classList.contains("is-sticky")) {

                    currentPlayer.classList.remove("is-sticky");

                    closeFloatVideo();

                    for (i = 0; i < ytVideoId.length; i++) {

                        if (currentPlayer == ytVideoId[i]) {

                            ytPlayerId[i].pauseVideo();

                        }

                    }

                    for (i = 0; i < videoTagId.length; i++) {

                        if (currentPlayer == videoTagId[i]) {

                            videoTagId[i].pause();

                        }

                    }



                } else {

                    for (i = 0; i < ytVideoId.length; i++) {

                        if (currentPlayer != ytVideoId[i]) {

                            ytVideoId[i].classList.remove("is-sticky");

                            closeFloatVideo();

                        }

                    }

                    for (i = 0; i < videoTagId.length; i++) {

                        if (currentPlayer != videoTagId[i]) {

                            videoTagId[i].classList.remove("is-sticky");

                            closeFloatVideo();

                        }

                    }

                }



            });

        }

    }

}



window.addEventListener('scroll', function () {



    inViewPortBol = inViewPort();

    if (currentPlayer) {

        if (!inViewPortBol && currentPlayer.classList.contains("is-playing")) {

            for (i = 0; i < ytVideoId.length; i++) {

                if (currentPlayer != ytVideoId[i]) {

                    ytVideoId[i].classList.remove("is-sticky");

                }

            }

            for (i = 0; i < videoTagId.length; i++) {

                if (currentPlayer != videoTagId[i]) {

                    videoTagId[i].classList.remove("is-sticky");

                }

            }

            currentPlayer.classList.add("is-sticky");

            openFloatVideo();

        } else {

            if (currentPlayer.classList.contains("is-sticky")) {

                currentPlayer.classList.remove("is-sticky");

                closeFloatVideo();

            }

        }

    }

});





function fullScreenPlay() {



    if (fullScreenIcon) {

        fullScreenIcon.addEventListener("click", function () {

            if (currentPlayer.requestFullscreen) {

                currentPlayer.requestFullscreen();

            } else if (currentPlayer.msRequestFullscreen) {

                currentPlayer.msRequestFullscreen();

            } else if (currentPlayer.mozRequestFullScreen) {

                currentPlayer.mozRequestFullScreen();

            } else if (currentPlayer.webkitRequestFullscreen) {

                currentPlayer.webkitRequestFullscreen();

            }

        });

    }

}



function inViewPort() {



    if (currentPlayer) {

        var videoParentLocal = currentPlayer.parentElement.getBoundingClientRect();

        return videoParentLocal.bottom > 0 &&

            videoParentLocal.right > 0 &&

            videoParentLocal.left < (window.innerWidth || document.documentElement.clientWidth) &&

            videoParentLocal.top < (window.innerHeight || document.documentElement.clientHeight);

    }

}



function openFloatVideo() {

    closeButton.style.display = "block";

    gradientOverlay.style.display = "block";

    fullScreenIcon.style.display = "block";

}



function closeFloatVideo() {

    closeButton.style.display = "none";

    gradientOverlay.style.display = "none";

    fullScreenIcon.style.display = "none";

}

在 codepen 中检查 CSS 和 HTML 要求。 谢谢!

关于javascript - YouTube 视频在向下滚动或粘滞时静音但仍在播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47707572/

相关文章:

javascript - vuejs-datepicker 从当前日期开始,添加样式

ios - AVCaptureVideoPreviewLayer 的比例

jquery - 容器 onclick 在视频元素和文本之间切换

javascript - 使用 WebSocket 进行文件传输

javascript - 如何修复 jTable 插件的 JSON.parse : unexpected character Line 550 jQuery. js 错误?

javascript - Bootstrap - 客户评价 Carousel 问题

javascript - jQuery .now() 不是唯一的

android - 如何播放 DCIM 文件夹中的 mp4 文件?

javascript - RxJS 如何从两个 promise 中获取第一个不为空的值

javascript - 显示元素内的多个字符