当达到CSS断点时触发事件

8

我有一组断点,每次通过一个断点时,我都想触发一个事件。目前,我正在使用$(document).resize(function(){}),但这与我的CSS断点不匹配,无论我使用windowdocument或任何其他选择器。

是否有一种检测媒体查询被触发的方法?以下是我的当前代码:

$( window ).resize(
    function() {
        if( $(window).width() < 500 ) {
            $(window).trigger("breakpoint-sm");
        }
        if( $(window).width() < 900 ) {
            $(window).trigger("breakpoint-md");
        }
    }
);

$(window).on(
    "breakpoint-md", function() {
        if($(window).width() < 900) {
            // this happens when below medium screen size
            alert( "breakpoint reached" );
        }
    }
);
@media screen and (max-width: 500px) {
    /* do mobile things */
}
@media screen and (max-width: 900px) {
    /* do mobile things */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

如果有更简单的方法来确定断点是否向上或向下通过,我愿意听取建议。

谢谢!


1
你可以将事件处理程序附加到 window.MatchMedia,当特定查询被触发时会被触发,就像这样 - Rory McCrossan
1个回答

11
我有一个解决方案,可以帮助你解决这个问题,我自己也用过。
基本上,你不能直接使用JavaScript检测断点,但是你可以检测断点引起的元素变化。当达到相应的断点时,.css-js_ref-* divs将变为可见状态。
<div class="css-js_ref">
    <div class="css-js_ref-sm" data-bp="sm"></div>
    <div class="css-js_ref-md" data-bp="md"></div>
</div>

然后,您可以使用JS检测最后一个可见元素是什么:

function currentBreakpoint() { return $('.css-js_ref > *:visible').first().attr('data-bp') };

这将返回您放入.css-js_ref标记中的断点名称,即sm

工作示例:

function currentBreakpoint() { return $('.css-js_ref > *:visible').first().attr('data-bp') };
var breakpointLength = $('.css-js_ref > *:visible').length;

$(window).on('resize', function () {

    var newBreakpointLength = $('.css-js_ref > *:visible').length;

    if (newBreakpointLength < breakpointLength) {
        breakpointLength = newBreakpointLength;
        $(window).trigger('breakpoint:up', [currentBreakpoint()]);

    }
    if (newBreakpointLength > breakpointLength) {
        breakpointLength = newBreakpointLength;
        $(window).trigger('breakpoint:down', [currentBreakpoint()]);
    }

});


$(window).on('breakpoint:down', function(event, bp){
    console.log(bp);
});
.css-js_ref * {
    display: none;
}

@media screen and (max-width: 500px) {
    .css-js_ref-sm {
        display: block;
        max-width: 500px;
    }
}
@media screen and (max-width: 900px) {
    .css-js_ref-md {
        display: block;
        max-width: 900px;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="css-js_ref">
    <div class="css-js_ref-sm" data-bp="sm"></div>
    <div class="css-js_ref-md" data-bp="md"></div>
</div>

用法:

// bp is the breakpoint that was reached
$(window).on('breakpoint:down', function(event, bp){
    if(bp === 'md') {
        // do stuff on below medium sized devices
    }
});

$(window).on('breakpoint:up', function(event, bp){
    if(bp === 'md') {
        // do stuff on above medium sized devices
    }
});

这个解决方案有些工作量,但非常灵活。它还意味着您只需要在一个地方定义断点,这对于DRY合规非常好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接