【问题标题】:Pause YouTube video on mouse leave鼠标离开时暂停 YouTube 视频
【发布时间】:2014-09-29 18:55:05
【问题描述】:

我正在创建一个函数,当用户将鼠标悬停在 div 上时插入 YouTube iframe,然后 when the user leaves div the video is paused. Everythings 工作正常,但当用户离开 div 时视频不会暂停。

小提琴:http://jsfiddle.net/508oknm7/20/

有什么想法吗?谢谢!

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

tag.src = "https://www.youtube.com/player_api";
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
$(".video_wrap").on({
    mouseenter: function () {

        player = new YT.Player($(this).attr('id'), {
            height: '240',
            width: '320',
            videoId: 'wJnnT1SGEsc',
            playerVars: {
            wmode: "transparent",
            controls: 0,
            showinfo: 0,
            rel: 0,
            modestbranding: 1,
            iv_load_policy: 3 //anottations
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });

        function onPlayerReady(event) {
            event.target.playVideo();
        }


    },
    mouseleave: function () {
        player.pauseVideo();
    }
});

【问题讨论】:

    标签: javascript jquery youtube-api


    【解决方案1】:

    API 可能还没有准备好 - 根据the youtube Iframe API,您需要实现 onYoutubeIframeAPIReady 函数。

    试试这个:

    var tag = document.createElement('script'),
        firstScriptTag = document.getElementsByTagName('script')[0];
    
    tag.src = "https://www.youtube.com/player_api";
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;
    function onYouTubeIframeAPIReady(){
    $(".video_wrap").on({
        mouseenter: function () {
    
            player = new YT.Player($(this).attr('id'), {
                height: '240',
                width: '320',
                videoId: 'wJnnT1SGEsc',
                playerVars: {
                wmode: "transparent",
                controls: 0,
                showinfo: 0,
                rel: 0,
                modestbranding: 1,
                iv_load_policy: 3 //anottations
                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
    
            function onPlayerReady(event) {
                event.target.playVideo();
            }
    
    
        },
        mouseleave: function () {
            player.pauseVideo();
        }
    });
    }
    

    请注意,这只是一个有根据的猜测,但如果您想要更具体的内容,可以提供一个 jsfiddle。

    编辑:This works for the first time

    之后它不起作用的原因是因为不再有mouseleave-因为不再有mouseenter-iframe完全覆盖了以前的div,因此您永远不会进入它,所以您不能离开它。

    你想为此使用 mouseout。

    【讨论】:

    • 谢谢,多个 div 呢?我需要它与多个@Etai 合作
    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多