jQuery:向内联样式函数添加重要内容

时间:2021-04-07 02:46:48

标签: jquery

我需要在添加内联样式的函数中添加“!important”,但是我有一种有趣的感觉,脚本的完成方式,它不起作用,我希望有人能对这个问题有所了解.

在我的 jQuery 示例中,如果我删除

 + ' !important'

脚本工作正常,但我需要添加重要的部分来覆盖我无权编辑的其他 CSS。

最终输出将如下所示:

  <a href="" class="eaContIcon" style="background:#0033ff !important;">
    Text
    <span class="customHex">#0033ff</span>
  </a>

HTML

<div class="mobContCon">

  <a href="" class="eaContIcon">
    Text
    <span class="customHex"></span>
  </a>

  <a href="" class="eaContIcon">
    Text
    <span class="customHex">#0033ff</span>
  </a>

  <a href="" class="eaContIcon">
    Text
    <span class="customHex">#ff00ff</span>
  </a>

</div>

CSS

a.eaContIcon {
  height: 40px;
  padding: 10px;
  background: #ff0000 !important;
  margin: 0 1px;
  color: #fff;
  text-decoration: none;
}

.customHex {
  display: none;
}

jQuery

$(document).ready(function() {

  $('.mobContCon a').each(function() {
    $(this).addClass('eaContIcon');
  });

  $('.eaContIcon').css('background', function() {
    return $(this).children('.customHex').text() + ' !important';

  });

});

这是一个FIDDLE

4 个答案:

答案 0 :(得分:1)

这是根据 Jeremy 对原始帖子的评论排序的

$(document).ready(function() {

  $('.mobContCon a').each(function() {
    $(this).addClass('eaContIcon');
  });

  $('.eaContIcon').attr('style', function() {
    return 'background:' + $(this).children('.customHex').text() + ' !important';

  });

});

答案 1 :(得分:0)

最佳实践是将 !important 转移到您的 .customHex 类中并在您的 jQuery 代码中将其删除。它应该是这样的:

.customHex {
display: none !important;
}

有关参考,您可以参考此链接: https://www.w3schools.com/css/css_important.asp

答案 2 :(得分:0)

我删除了可能不需要的额外 js 代码。你可以试试这个,它会起作用。

$(document).ready(function() {
  $('.mobContCon a').each(function() {
      let objthis = $(this);
      let backgroundColor = objthis.children('.customHex').text() + ' !important';

      objthis.addClass('eaContIcon');
      objthis.attr("style","background :" + backgroundColor);

     });
});

答案 3 :(得分:0)

条件(三元)运算符empty or not的帮助下,检查十六进制颜色代码是override background color
我希望以下代码段对您有很大帮助。

$(document).ready(function () {
    $('.mobContCon a').each(function () {
        var _this = $(this);
        _this.addClass('eaContIcon');
    
        var getColorCode = _this.find('.customHex').text();
        getColorCode != ''?  _this.attr("style", "background:" + getColorCode + '!important'): ''
    });
});
a.eaContIcon {
    height: 40px;
    padding: 10px;
    background: #ff0000 !important;
    margin: 0 1px;
    color: #fff;
    text-decoration: none;
}
.customHex {
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="mobContCon">
    <a href="" class="eaContIcon">
        Text
        <span class="customHex"></span>
    </a>
    <a href="" class="eaContIcon">
        Text
        <span class="customHex">#0033ff</span>
    </a>
    <a href="" class="eaContIcon">
        Text
        <span class="customHex">#ff00ff</span>
    </a>
</div>

相关问题