在脚本中包含两个 window.matchMedia

Including two window.matchMedia into script

我正在尝试添加:

var mql = window.matchMedia("(max-width: 480px)"), window.matchMedia("(max-height: 479px)");

立即进入我现有的脚本,其中只有:

var mql = window.matchMedia("(max-width: 480px)");

当我添加上面提到的第二个 .matchMedia 时,脚本根本没有触发。

我试过添加两个变量:

var mqls = [ 
  window.matchMedia("(max-width: 480px)"),
  window.matchMedia("(max-height: 479px)")
];

function mediaqueryresponse(mql){
  document.getElementById("match1").innerHTML = mqls[0].matches // width: 480px media match?
  document.getElementById("match2").innerHTML = mqls[1].matches // width: 479px media match?
}

这是添加 max-height 之前运行的脚本:jsFiddle。请注意脚本位于 js 面板的底部。顶部脚本用于 TweenMax 以动画线条。

这是添加了变量的脚本:jsFiddle.

如果你想让smallBlock()动画变成运行当min-width479pxmin-height480px 然后我认为在查询之间添加逗号 , 应该可以解决问题。

看看 this jsFiddle 并测试它是否产生您正在寻找的结果。

JavaScript:

var mql = window.matchMedia('(min-width: 479px), (max-height: 480px)');
function smallBlock() {
    setTimeout(function () {
        TweenLite.defaultEase = Linear.easeNone;
        TweenLite.set('.square', { visibility: 'visible' });
        var tl = new TimelineLite();
        tl.fromTo('.l1', 2, { height: 0 }, { height: 27 });
        tl.fromTo('.l2', 3, { width: 0, }, { width: 45 });
        tl.fromTo('.l3', 2, { height: 0 }, { height: 27 });
        tl.fromTo('.l4', 3, { width: 0 }, { width: 45 });
        tl.timeScale(4);
    }, 600);
};
function largeBlock() {
    setTimeout(function () {
        TweenLite.defaultEase = Linear.easeNone;
        TweenLite.set('.square', { visibility: 'visible' });
        var tl = new TimelineLite();
        tl.fromTo('.l1', 2, { height: 0 }, { height: 227 });
        tl.fromTo('.l2', 3, { width: 0, }, { width: 445 });
        tl.fromTo('.l3', 2, { height: 0 }, { height: 227 });
        tl.fromTo('.l4', 3, { width: 0 }, { width: 445 });
        tl.timeScale(4);
    }, 600);
}
function handleScreen(mql) {
    mql.matches ? smallBlock() : largeBlock();
}
mql.addListener(handleScreen);
handleScreen(mql);

希望这对您有所帮助。 CSS 媒体查询的文档可以在 here.

找到