【问题标题】:Making an inline css to be more powerful than an external !important?使内联 css 比外部更强大!重要?
【发布时间】:2013-09-14 13:38:18
【问题描述】:

我有一个滑块脚本和一个模板外部样式表,我必须使用它们。我被指示只使用 custom.css 来覆盖模板外部样式表。

我的问题是,模板中的滑块 css 有一个 !important。滑块脚本计算图像的宽度和高度,并通过内联 css 插入。我希望内联 css 在级联中发挥更大的作用,而不是模板样式表中的 !important 。

例如:

在 html doc 中,加载滑块脚本后:

<img src="slide1.jpg" style="width: 980.2545515px;" />

在模板样式表中:

img {
width: 500px !important;
}

我尝试使用jquery,例如:

$("img").css("width","500px");

但是,它不会覆盖任何内容。请注意,我需要自动生成的宽度来覆盖任何内容。但我似乎找不到覆盖宽度的方法:500px !important - width: auto/width: inherit 也不起作用。

有什么解决办法吗?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

使用.css() 方法实际上无法做到这一点,但可以使用.attr() 方法做到这一点,但这会覆盖您已有的任何其他内联样式。

$('img').attr('style', 'width:500px !important;')

这是一个演示:http://jsfiddle.net/AGuvg/

【讨论】:

  • 感谢您抽出宝贵时间回答。但是,它仅适用于加载时滑块的第一个图像。另外,我不想设置一个恒定的宽度。我希望滑块脚本自动生成的宽度很重要。有什么方法可以将 !important 附加到内联 css 中?
  • 是的,你可以使用上面的作为基础。
【解决方案2】:

不是 jquery 本身,但你可以像这样使用setProperty

$('img')[0].style.setProperty( 'width', '500px', 'important' );

【讨论】:

    【解决方案3】:

    您可以动态生成额外的样式表。此示例适用于 Chrome,但我不知道它在其他浏览器中的行为方式:http://jsfiddle.net/mj2Um/

    var stylesheet;
    function setWidth(value) {
        stylesheet && stylesheet.remove();
        stylesheet = $('<style>img{width:' + value + 'px !important;}</style>');
        stylesheet.appendTo('body');
    }
    setWidth(150);
    

    【讨论】:

      【解决方案4】:

      如果您需要应用动态生成的宽度,唯一的方法是在内联样式中添加!important。你可以这样做:

      var styleAttr = $(".slider-image").attr("style");
      
      styleAttr += " !important";  
      /* ^^ assumes styleAttr is just 'width: 980.2545515px' and so 
      becomes 'width:   980.2545515px !important' - if the style attribute is more 
      complex than this you'd need a bit more sophisticated parsing of it */
      
      $(".slider-image").attr('style', styleAttr);
      

      这将强制动态宽度覆盖样式表!重要的一个。

      【讨论】:

        猜你喜欢
        • 2012-10-29
        • 2021-09-10
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多