@media最小大小-仅在特定窗口大小时激活



我有一个javascript,我只想在窗口大小为1326px的最小值时工作

这就是我所做的,但它不起作用。无论窗口大小如何,脚本都将运行。

如果你看一下前两行,那是我用来检测窗口大小的。

var mq = window.matchMedia( "(min-width: 1326px)" );
if (mq.matches)
    {
    function openNav() {
        document.getElementById("mySidenav").style.width = "250px";
        document.getElementById("sidebar-loc").style.marginLeft = "250px";
    }
    function closeNav() {
        document.getElementById("mySidenav").style.width = "0";
    document.getElementById("sidebar-loc").style.marginLeft= "0";
    }
    ( function($) {
    $(document).ready(function () {
        slider();
    });
    } ) ( jQuery );
    ( function($) {
    $(window).scroll(function () {
    slider();
    });
    } ) ( jQuery );
    function slider() {
        if (document.body.scrollTop > 700)
            ( function($) {
            $('#sliderr').stop().animate({"margin-left": '0'});
            } ) ( jQuery );
        else
            ( function($) {
            $('#sliderr').stop().animate({"margin-left": '-200'});
            } ) ( jQuery );
    }
    (jQuery);
    ( function($) {
    $(document).ready( function() {
        $("#show_arrow").hide(); //hide your div initially
        $(window).scroll(function() {
            if($(window).scrollTop() > 700) { //scrolled past the other div?
                $("#show_arrow").show(); //reached the desired point -- show div
            }
            else($(window).scrollTop() < 700) 
                $("#show_arrow").hide();
        });
    });
    } ) ( jQuery );
    }

您需要添加一个侦听器

有点像这样

if (matchMedia) {
  var mq = window.matchMedia("(min-width: 1326px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

这不起作用,因为您只在代码运行时检查媒体查询是否匹配一次。

解决方案是将整个代码封装在mq.addListener(function (e) { code })中。e对象也具有属性.matches,或者您仍然可以使用mq.matches,该对象也会在更改时更新。

还请记住,此功能仍处于工作草案阶段,在一些较旧的浏览器中不支持。如果你想在这些浏览器中获得支持,你必须监听window resize事件,并根据窗口宽度确定媒体查询是否匹配。

最新更新