使用Jquery对CSS更改的触发器事件? [英] Trigger event using Jquery on CSS change?

查看:113
本文介绍了使用Jquery对CSS更改的触发器事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇有没有一个事件监听器,或者是一种方法来构造一个当CSS发生变化时触发的方法?

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
  }
});

这很好,但每次用户更改屏幕时,它都会调用监听器,只有它的火只有当按钮的CSS改变。我希望这是有意义的。

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.

例如这是我想要的

$('#search-button').cssEventListenerOfSomeKind(function() {
  alert('the display changed');
});


推荐答案

绑定到 resize 是你最好的选择(我相信)。更改元素的CSS时没有触发任何事件。不过,您可以通过缓存所使用的选择器来优化一点:

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
    }
});

也可以使用 $(window).width c $ c>检查视口的宽度:

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

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
        }
    }
});

这将阻止 resize 事件处理程序每​​季度运行一次以上。

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

这篇关于使用Jquery对CSS更改的触发器事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆