扩展jquery.css函数以覆盖!重要样式

时间:2015-05-28 18:05:07

标签: javascript jquery html css

我正在编写一个邮件模板编辑器,用户可以使用我们的可视化编辑器导入他们现有的模板并重新设计模板。如果用户更改的元素具有!important 样式属性;我们必须使用 jquery.css 覆盖该属性。

实施例

 <div id="sendwrapper">
      <button> Send </button>
 </div>

风格

#sendwrapper * {
   color:white !important;
}

我想将颜色白色更改为绿色。我试过这个插件https://github.com/premasagar/important/blob/master/important.js。这个插件不是那么聪明,它为所有属性设置!important ,但我希望它只应为设置!important 的属性设置!important

5 个答案:

答案 0 :(得分:1)

不必使用太多的编译代码jquery为您提供了覆盖css规则的便利性

只需使用此

即可
 $('#sendwrapper').children().css("cssText", "color: green !important;");

我正在使用children(),因为我可以看到你已经应用了这样的css:#sendwrapper *所以要考虑*我正在使用children()

cssText只会覆盖您当前的CSS

您正在创建的模块类型也是最合适的方法。

DEMO:http://jsfiddle.net/6L0p5gk9/

因此无需扩展jQuery CSS功能。您正在寻找的功能已经存在

答案 1 :(得分:0)

jQuery.style(源代码中搜索style:)的定义中,找到行

style[ name ] = value;

在此之后,添加以下代码:

// Get the computed value after setting the desired value without !important
var computedValue = jQuery.css(elem, name);

// Check if browser supports adding inline important styles
if(typeof style.setProperty == 'function') {

    // Set the desired value with !important
    style.setProperty(name, value, "important");

    // Check if the computed value is still the same
    if(computedValue === jQuery.css(elem, name)) {

        // Then !important is not needed, so remove it
        style.setProperty(name, value);
    }
}

答案 2 :(得分:0)

我编写了一个首先尝试添加所需规则的插件,如果没有更改,则会添加If TFDocuments.CheckState = CheckState.Checked Then My.Computer.FileSystem.CopyDirectory(lblPathStatus.Text & "Documents\", "\\7server\Customer Backups\Uploads\" & txtCustomerName.Text & "\Documents\") End If 规则。据我所知,如果规则设置为!important,则无法测试,但如果在尝试使用JS修改它时值不会改变,则可以假设情况就是这样。

简而言之,它仅在必要时设置!important声明:

!important
$.fn.extend({
    cssi:function(obj){
        var $target=this;
        $.each(obj,function(i,e){
            var initialVal=$target.css(i);
            $target.css(i,e);
            if($target.css(i)===initialVal && initialVal!==e){ //add !important only if the value didn't change and you're not trying to set it to the value it already had
                if(!isNaN(e)) e+="px";
                e+=" !important";
                $target.css(i,""); // clear any prior rules
                $target[0].style.cssText+=camelToDash(i)+":"+e;
            }         
        });
        return this;
    }
});

function camelToDash(str) {
    return str.replace(/\W+/g, '-')
    .replace(/([a-z\d])([A-Z])/g, '$1-$2')
    .toLowerCase();
}




//Demo
$(function(){
    $("div").cssi({
        backgroundColor:"blue",
        height:100,
        width:100,
        color:"red"
    });
});
div{ /*Just something to test it with*/
    height: 50px !important;
    width:50px;
    background-color:red !important;
    color:green !important;
}

这里还有Fiddle

答案 3 :(得分:0)

如果浏览器支持Proxy(ES6),则可以使用此插件:

if ( // Check browser support
  window.Proxy
  && window.CSSStyleDeclaration
  && CSSStyleDeclaration.prototype.setProperty
) {
  jQuery.cssHooks = new Proxy(jQuery.cssHooks, {
    get: function(hooks, name) {
      return new Proxy(hooks[name] || (hooks[name] = {}), {
        has: function (hook, setget) {
          return setget === 'set' || setget in hook;
        },
        get: function (hook, setget){
          if(setget !== 'set') return hook[setget];
          return function(elem, value, extra) {

            // Use the cssHook setter, if any
            if(hook.set) {
              value = hook.set(elem, value, extra);
              if(value === void 0) return; // No value
            }

            // Set the desired value without !important
            elem.style[ name ] = value;

            // Get the computed value
            var computedValue = jQuery.css(elem, name);

            // Check if the computed value is the desired one
            if(computedValue === value) return; // OK

            // Set the desired value with !important
            elem.style.setProperty(name, value, "important");

            // Check if the computed value has changed
            if(computedValue !== jQuery.css(elem, name)) return; // OK

            // Otherwise !important is not needed, so remove it
            elem.style.setProperty(name, value);
          }
        }
      });
    }
  });
}

&#13;
&#13;
// Plugin compiled with Closure Compiler
window.Proxy&&window.CSSStyleDeclaration&&CSSStyleDeclaration.prototype.setProperty&&(jQuery.cssHooks=new Proxy(jQuery.cssHooks,{get:function(f,b){return new Proxy(f[b]||(f[b]={}),{has:function(b,a){return"set"===a||a in b},get:function(e,a){return"set"!==a?e[a]:function(d,c,a){if(e.set&&(c=e.set(d,c,a),void 0===c))return;d.style[b]=c;a=jQuery.css(d,b);a!==c&&(d.style.setProperty(b,c,"important"),a===jQuery.css(d,b)&&d.style.setProperty(b,c))}}})}}));

// The elements in the collection that need !important will use it
$('.color').css('color', 'blue');

// The plugin is compatible with custom cssHooks
$.cssHooks.opacity.set = function(elem, value) { return value/4 + '' };
$('.opacity').css('opacity', .8);
&#13;
.color {
   color: red;
}
.color.important {
   color: red !important;
}
.opacity.important {
   opacity: 1 !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="color">color: blue</div>
<div class="color important">color: blue !important</div>
<div class="opacity important">opacity: .2 !important</div>
&#13;
&#13;
&#13;

请注意,上面的代码会在jQuery.cssHooks中自动创建对象,例如查找$.cssHooks.color将存储$.cssHooks.color = {}。如果您不想要,请使用此其他代码。

&#13;
&#13;
if ( // Check browser support
  window.Proxy
  && window.CSSStyleDeclaration
  && CSSStyleDeclaration.prototype.setProperty
) {
  jQuery.cssHooks = new Proxy(jQuery.cssHooks, {
    get: function(hooks, name) {
      return new Proxy(hooks[name] || {}, {
        has: function(hook, setget) {
          return setget === 'set' || setget in hook;
        },
        set: function(hook, setget, value) {
          if(!hooks[name]) hooks[name] = hook;
          hook[setget] = value;
          return true;
        },
        get: function(hook, setget){
          if(setget !== 'set') return hook[setget];
          return function(elem, value, extra) {

            // Use the cssHook setter, if any
            if(hook.set) {
              value = hook.set(elem, value, extra);
              if(value === void 0) return; // No value
            }

            var style = elem.style;

            // Set the desired value without !important
            style[ name ] = value;

            // Get the computed value
            var computedValue = jQuery.css(elem, name);
            
            // Check if the computed value is the desired one
            if(computedValue === value) return; // OK

            // Set the desired value with !important
            style.setProperty(name, value, "important");

            // Check if the computed value has changed
            if(computedValue !== jQuery.css(elem, name)) return; // OK

            // Otherwise !important is not needed, so remove it
            elem.style.setProperty(name, value);
          }
        }
      });
    }
  });
}

// The elements in the collection that need !important will use it
$('.color').css('color', 'blue');

// The plugin is compatible with custom cssHooks
if(!$.cssHooks.opacity) $.cssHooks.opacity = {};
$.cssHooks.opacity.set = function(elem, value) { return value/4 + '' };
$('.opacity').css('opacity', .8);
&#13;
.color {
   color: red;
}
.color.important {
   color: red !important;
}
.opacity.important {
   opacity: 1 !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="color">color: blue</div>
<div class="color important">color: blue !important</div>
<div class="opacity important">opacity: .2 !important</div>
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

//清除!important css

$('#elementToChange').css('background-color', '');

$('#elementToChange').css('background-color', 'blue');

或者在单行中:

$('#elementToChange')
    .css('background-color', '')
    .css('background-color', 'blue');

或者您可以通过CSS中的预定义类为其添加一个类。