Pause YouTube video on mouseleave

2019-03-04 16:26发布

问题:

I have created a function which inserts an YouTube iframe when user hovers on a div and then when mouse leaves the div the video is paused. Everything works fine but the video is paused only the first time and when you click play again and then leave div it dosen't pause. Any ideas? Thanks.

Fiddle: http://jsfiddle.net/508oknm7/27/

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).children().attr('id'), {
            height: '240',
            width: '320',
            videoId: '-NschES-8e0',
            playerVars: {
            wmode: "transparent",
            controls: 0,
            showinfo: 0,
            rel: 0,
            modestbranding: 1,
            iv_load_policy: 3 //anottations
            },
            events: {
                'onReady': onPlayerReady
            }
        });

        function onPlayerReady(event) {
            player.setVolume(10);
            event.target.playVideo();
        }


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

    }
});