【问题标题】:jQuery .css not applying on parent container [duplicate]jQuery .css 不适用于父容器 [重复]
【发布时间】:2018-08-24 09:59:39
【问题描述】:

我正在尝试使用以下语句应用内联 css。

$('.WarningCount').parent().css('margin-left', '-1.4% !important;');

但它不起作用,它不仅仅被应用。我在开发者控制台中看不到这种风格。我必须覆盖整个样式才能使其正常工作。

$('.WarningCount').parent().attr('style', 'margin-left:-1.4% !important;');

任何原因可能是这里的真正问题。

【问题讨论】:

  • 您能否创建minimal reproducible example 供我们查看,我们还需要 html 来尝试查找错误,可能还需要适用于父元素的其他 css 规则。跨度>
  • 请也发布您的html
  • 查看副本以解决当前问题。不过,我建议您构建 CSS 选择器以正确使用选择器优先级。这是一个更可扩展的修复程序。
  • 我建议使用 JQuery 文档中提到的类,$('.WarningCount').parent().addClass('margin-left-added-class')

标签: jquery css


【解决方案1】:

取自jQuery documentation:

注意:.css() 忽略 !important 声明。所以,语句 $("p" ).css( "color", "red !important" ) 不会改变所有的颜色 页面中的段落变为红色。强烈建议使用类 反而;否则使用 jQuery 插件。

不过,你可以参考this answer并使用cssText属性

const target = $('.WarningCount').parent();
target.css('cssText', target.attr('style')+'margin-left: -1.4% !important;');

【讨论】:

  • OP 声明他们已经这样做了。更好的解决方案是正确构建 CSS 规则,这样您就根本不需要使用 !important
  • The OP states they've already done that -> 做了什么?
  • 使用css() 解决方案。您展示的 parent().css() 示例与 OP 中存在相同的问题 - 您甚至从文档中获取的报价解释了为什么这不起作用。此外,如果您认为另一个问题有解决方案,请投票将其作为重复项关闭。请勿使用链接为此问题添加其他答案,因为它会阻止 Roomba 删除此问题。
  • 你是对的。让我解决
  • 你错了。 PO的问题是Any reason what could be the real issue here.。答案在我引用的 jQuery 文档中。
【解决方案2】:

使用 JSON 格式而不是逗号格式。像这样,

$(".WarningCount").parent().css({"margin-left": "-1.4%"});

【讨论】:

  • 这仍然行不通。
【解决方案3】:
$( '.WarningCount' ).parent().each(function () {
    this.style.setProperty( 'margin-left', '-1.4%', 'important' );
});

元素样式对象或 CSSStyleDeclaration 的一部分的 .setProperty 方法允许您传递代表优先级的第三个参数。因此,您将使用自己的 !important 值覆盖 !important。

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

希望这可以消除对此的任何疑问。

【讨论】:

  • 请添加您的代码的简短说明。
猜你喜欢
  • 1970-01-01
  • 2021-02-08
  • 2018-09-05
  • 2020-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多