显示类时,将类添加到许多其他元素

时间:2016-05-19 06:52:10

标签: javascript class toggle

我有一个名为

的班级
.informations

当显示这个类时,我很乐意将类添加到其他元素中,例如

#logo
#totale
.submenu
#fp-nav

所以将字体颜色从黑色更改为白色。 有没有办法实现这个目标?

选中此JsFiddle

1 个答案:

答案 0 :(得分:1)

如果您使用jQuery,则可以使用此扩展程序(找到here):

(function($) {
    $.each(['show','hide'], function(i, val) {
        var _org = $.fn[val];
        $.fn[val] = function() {
            this.trigger(val);
            _org.apply(this, arguments);
        };
    });
})(jQuery);

工作JSFiddle

HTML

<div class="informations">
  When this is shown, other elements get white color.
</div>

<div id="logo">
  Logo
</div>

<div id="totale">
  Totale
</div>

<div class="submenu">
  Submenu
</div>

的JavaScript

$(".informations").on("show", function() {
    $("#logo, #totale, .submenu, #fp-nav").addClass("white-text");
});

setTimeout(function() {
    $(".informations").show();
}, 2000);

CSS

.white-text {
  color: #fff;
  background-color: #000;
}

.informations {
  display: none;
}

更新1

尝试this,找到here

的JavaScript

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
      if(mutationRecord.target.style.display !== "none") {
        console.log('display changed, now visible!');
        $("#logo, #totale, .submenu, #fp-nav").addClass("white-text");
      } else {
        console.log('display changed, now visible!');
        $("#logo, #totale, .submenu, #fp-nav").removeClass("white-text");
      }
    });    
});

observer.observe($(".informations")[0], { attributes : true, attributeFilter : ['style'] });

setTimeout(function() {
    $(".informations").show();
  setTimeout(function() {
    $(".informations").hide();
  }, 2000);
}, 2000);