达到CSS断点时触发事件

Sus*_*ium 4 html javascript css jquery breakpoints

我有一组断点,我想在每次传递一个事件时触发一个事件。目前,我正在使用$(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" );
        }
    }
);
Run Code Online (Sandbox Code Playgroud)
@media screen and (max-width: 500px) {
    /* do mobile things */
}
@media screen and (max-width: 900px) {
    /* do mobile things */
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

如果有更简单的方法知道断点是向上还是向下传递,我将很乐意听到。

谢谢!

Mat*_*att 5

我已经用我自己解决了您的确切问题。

基本上,您无法使用JavaScript直接检测断点,但是可以检测由断点引起的元素更改。.css-js_ref-*当达到各自的断点时,div将变为可见。

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

工作示例:

<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>
Run Code Online (Sandbox Code Playgroud)
function currentBreakpoint() { return $('.css-js_ref > *:visible').first().attr('data-bp') };
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)

用法:

// 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
    }
});
Run Code Online (Sandbox Code Playgroud)

该解决方案需要一些工作,但用途非常广泛。这也意味着您只需要在一个地方定义断点,这对DRY合规性非常有用