简体   繁体   English

根据不断变化的内联变量值添加类?

[英]Adding a class based on a changing inline variable's value?

How do we assign a class based on what an inline variable's value changes to? 我们如何根据内联变量的值更改为哪个类?

Here is the demonstration which is much easier to understand: http://jsfiddle.net/eYGr5/75/ 这是更容易理解的演示: http : //jsfiddle.net/eYGr5/75/

Basically, another script (I don't want to touch) is assigning an inline style to a div. 基本上,另一个脚本(我不想讲)是为div分配内联样式。 I want to identify when "IF" this style's value has changed, to apply a class to a certain element. 我想确定何时“ IF”此样式的值更改,以将类应用于特定元素。

Here is the minified non-interactive copy of the code: 这是代码的最小化非交互式副本:

HTML: HTML:

<div class="mm-active">mm-active</div>

<div class="mm-container" style="color:DarkGreen;">mm-container: By hovering here, the jQuery should look up the new inline style (DeepPink) and ONLY because of that inline style, turn mm-active lime green!</div>

CSS: CSS:

.activefix {
    background:Lime;
}

jQuery: jQuery的:

// This function gets the value of an inline style property, (Source: bit.ly/1er8vJ2):
(function($) {
    $.fn.inlineStyle = function (prop) {
        return this.prop("style")[$.camelCase(prop)];
    };
}(jQuery));

// Now how do we assign a class based on what this inline variable changes to?
if ($(".mm-container").inlineStyle("color") == 'DeepPink') {
    $('.mm-active').addClass('activefix'); // This should apply "Lime" to mm-active
}

IF the script that is adding the class is using jquery's .addClass() method, you should overwrite that method to add an event listener, then bind that listener to the event that is causing it to fire when .addClass is called on that event. 如果添加类的脚本使用jquery的.addClass()方法,则应覆盖该方法以添加事件侦听器,然后将该侦听器绑定到在该事件上调用.addClass时导致其触发的事件。

(function(){
 var originalAddClassMethod = jQuery.fn.addClass;
 jQuery.fn.addClass = function(){
     var result = originalAddClassMethod.apply( this, arguments );
     jQuery(this).trigger('cssClassChanged');
     return result;
 }
})();


$(function(){
 $("#Your Element To Add Handler To").bind('cssClassChanged', function(){ 
     $('.mm-active').addClass('activefix');
 });
});

Colour is handled differently across browsers, some may return the rgba code and some the hex (regardless fo what you assign to them). 不同浏览器对颜色的处理方式不同,有些可能返回rgba代码,有些可能返回十六进制(无论您分配给它们什么)。 I'd shy away from checking explicit colour names, but if you really insist, you need to write a function to read rgba/hex and translate them to your HTML entities. 我会回避检查显式的颜色名称,但是如果您真的坚持,则需要编写一个函数来读取rgba / hex并将其转换为HTML实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM