LoginSignup
6

More than 5 years have passed since last update.

レガシーIEでのYouTube(iframe)対応

Last updated at Posted at 2015-12-13

YouTube(を始めとするiframe系)関連のTips(随時更新)

z-index問題

これはたぶんいちばん有名ですね。
IE9ぐらいまで、普通にiframeにzIndexを設定していても、値を無視して前面にでてきます。
対応は wmode=transparent を追加してあげるだけ

直接 HTMLに書くなら

<iframe src="http://www.youtube.com/embed/***?wmode=transparent" width="560" height="315"></iframe>

YouTube Plyaer API経由なら

player = new YT.Player('player', {
    height: '1920',
    width: '1080',
    videoId: '***',
    playerVars: {
        wmode: 'transparent'
    }
});

透明色すり抜け問題

これも種類的には上の重なり順問題に関連しているのですが、
よく背景動画として全画面でYouTubeを埋め込んで、手前でわちゃわちゃやるサイトがあると思います。
下のサンプルは例として、全画面でYouTubeが再生されて、マウスを動かしたらSKIPボタンがでるという想定です。

<div class="container">
    <iframe src="***?wmode=transparent" class="player"></iframe>
    <div class="player-cover"></div>
    <a class="btn-skip">SKIP</a>
</div>

.container {
    position: relative;
}

.player {
    position: absolute;
    z-index:0;
    // etc...
}

.player-cover {
    position: absolute;
    z-index: 10;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

.btn-skip {
    display: none;
    position: absolute;
    z-index:20;
    // etc...
}
// ie だと window.attachEvent('onmousemove', func);
window.addEventListener('mousemove', function () {
    document.querySelector('.btn-skip').style.display = 'block';
});

シンプルにするとこんな感じです。
キーとなるのは .player-coverです。
これがiframeに前に覆いかぶさるので、iframeの上でclickやmousemoveをしても、すべて.player-coverに巻き取られ、mousemoveイベントも問題なく発火するという仕組みです。

なにも難しいことはないですね。
単純明快。
そしてこれがレガシーIEだとうまくいきません。ふぁっきゅーです。

原因は、.player-coverに背景系のプロパティが指定されてないためです。
モダンブラウザだと、上記は「透明なガラス」状態になるので、透明ではありますが、突き抜けることはありません。
ただしレガシーIEだと「なにもない」状態になってしまうため、mousemoveやclickは.player-coverで巻き取られる事なく(イベントが発火することなく)iframeに流れていってしまいます。

.player-cover {
    position: absolute;
    z-index: 10;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-image:url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7);
}

というわけで 1x1の透明色GIF画像を背景画像に設定してあげれば万事解決です。

<追記:2015/12/14>
もともと .player-cover でなく.containerのbefore要素に値を設定していたのですが、
IE7、IE8だと擬似要素の重なり順周りにバグがあるので、beforeからdivに変更しました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6