Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - Trigger event using Jquery on CSS change?

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 want to know if there's a way to attach a listener to see when those media queries kick in and out. For example I have a media query that hides a button at certain screen widths

@media screen and (max-width: 480px) {
  #search-button {
    display: none;
  }
}

What event listener would I use to detect when that display changes? I'm currently doing this:

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

Which works fine, but it calls the listener every time the user changes the screen and I'd rather just have it fire only when the css of the button changes. I hope that makes sense.

for example this is what I'd like

$('#search-button').cssEventListenerOfSomeKind(function() {
  alert('the display changed');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...