如何将以下事件侦听器转换为特定于供应商的侦听器?

时间:2016-04-14 02:02:09

标签: javascript

如果用户在横向方向退出全屏时,我使用以下功能触发事件:

document.addEventListener('webkitfullscreenchange', () => {
  if (util.isLandscape()) {
    console.log('EXITED')
  }
}, false)

我想添加mozfullscreenchange和MS等...

如何构建一个实现此功能的函数?

1 个答案:

答案 0 :(得分:2)

简单(天真)的方法可能是:

document.addEventListener('mozfullscreenchange', fullScreenFunction, false)
document.addEventListener('webkitfullscreenchange',fullScreenFunction, false)
document.addEventListener('msfullscreenchange', fullScreenFunction, false)
//etc
function fullScreenFunction()
{
 if (util.isLandscape()) {
        console.log('EXITED')
      }    
}

或者你可以尝试测试哪个前缀存在,然后只绑定一个存在的事件句柄。

粗略的想法是这样的:

var prefixes = ['webkit', 'moz', 'ms', 'o'];
var prefixToUse = '';
for (var i = 0; i < prefixes.length; i++) {
//This checks against the document object for that event.
//It will start with on eg onmsfullscreenchange or onwebkitfullscreenchange
    if( 'on' + prefixes[i] + 'fullscreenchange' in document) {
        prefixToUse = prefixes[i];
        break;
    } 
}
document.addEventListener(prefixToUse + 'fullscreenchange', fullScreenFunction, false);

function fullScreenFunction()
{
    if (util.isLandscape()) {
        console.log('EXITED')
    }
}