Trigger event using Jquery on CSS change?

后端 未结 3 1905
不思量自难忘°
不思量自难忘° 2020-12-19 01:38

I\'m curious is there an event listener or perhaps a way to construct a method that will trigger when a CSS change happens?

My stylesheet uses media queries and I wa

相关标签:
3条回答
  • 2020-12-19 01:55

    I know this is old but I managed to solve it with this logic

        // set width and height of element that is controlled by the media query
        var page_width = $page.width();
        var page_height = $page.height();
    
    
        $window = $(window).resize(function(){
            if( $page.width() != page_width ) {
                // update page_width and height so it only executes your 
                // function when a change occurs
                page_width = $page.width();
                page_height = $page.height();
                // do something
                // ...
            }
        });
    
    0 讨论(0)
  • 2020-12-19 01:56

    Binding to the window.resize is your best option (I believe). There isn't any event fired when you change an element's CSS. You can however optimize a bit by caching the selector used:

    var $searcButton = $('#search-button');
    $(window).resize(function() {
        if($searcButton.css("display") == "none") {
            //do something
        } else {
            //do something else
        }
    });
    

    Or you can use $(window).width() to check the width of the viewport:

    var $window = $(window);
    $window.resize(function() {
        if($window.width() <= 480) {
            //do something
        } else {
            //do something else
        }
    });
    

    UPDATE

    You can always throttle your own event handler:

    var $window   = $(window),
        resize_ok = true,
        timer;
    
    timer = setInterval(function () {
        resize_ok = true;
    }, 250);
    
    $window.resize(function() {
        if (resize_ok === true) {
            resize_ok = false;
            if($window.width() <= 480) {
                //do something
            } else {
                //do something else
            }
        }
    });
    

    This will prevent the code in your resize event handler from running more than once every quarter second.

    0 讨论(0)
  • 2020-12-19 02:10

    If it is only a one time event you could try to unbind the event.

    http://api.jquery.com/unbind/

    0 讨论(0)
提交回复
热议问题