如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式

How to control (avoid) styling of nested html elements when using jQuery if classes are not an option?

本文关键字:避免 控制 jQuery 嵌套 样式 元素 html 一个 如果 选项      更新时间:2023-09-26

我正在使用jQuery在Wordpress主题中实现动态样式功能。jQuery使用内联样式这一事实使我受到挑战,这可能会产生嵌套元素可能被选择器定位的效果,即使相同的选择器在CSS规则中不起作用。为了说明我的意思,请看一下这个JSFiddle。

.HTML:

<p>
  This is normal text
  <br>
  <br>
  <em>This is italic text</em>
  <br>
  <br>
  <strong>This is bold text</strong>
  <br>
  <br>
  <strong><em>This is bold italic text</em></strong>
  <br>
  <br>
  <em><strong>This is also bold italic text</strong></em>
  <br>
  <br>
</p>
<button>
  Style it!
</button>

.CSS:

p em strong,
p strong em {
      color: red;
    }
p strong {
  color: blue;
}

j查询:

(function($) {
  $('button').on('click', function() {
    $('p strong').css('color', 'turquoise');
  });
})(jQuery);

如图所示,粗体文本的 CSS 样式仅按预期对粗体文本生效,但使用 jQuery - 使用相同的选择器,将标记作为嵌套标记的粗斜体文本的实例也会受到影响。

是否可以像示例中那样进行不包含嵌套元素的 jQuery 选择?显然,如果我可以使用类,解决方案会很简单,但在这种情况下我不能。

如果我将 !important 选项添加到最初设置为红色样式的元素中,我会得到我想要的,但如果可能的话,我真的很想避免这种情况。谢谢。

如果需要解决特定情况,则可以使用 jQuery .not() 方法从选择中排除选择。对于这种情况:

$('p strong').not('p em strong').css('color', 'turquoise');

这并不能解决 jQuery .css() 方法编辑元素的 style 属性的总体问题,当浏览器确定要应用的样式时,该属性会为样式增加一个数量级的特异性。

一种替代方法是创建一个JavaScript函数,该函数将为DOM添加新的CSS样式。示例函数可能如下所示:

var createCSSStyle = (function() {
    var styleSheet = null;
    return function(selector, cssOptions) {
        if (styleSheet == null) {
            styleSheet = document.createElement('style');
            styleSheet.type = 'text/css';
            document.getElementsByTagName('head')[0].appendChild(styleSheet);
        }
        var text = " " + selector + " {";
        for(var prop in cssOptions)
            text += prop + ":" + cssOptions[prop] + ";";
        text += "}";
        styleSheet.innerHTML += text;
    };
})();

并使用它:

createCSSStyle('p  strong', { 'color' : 'turquoise' });

这是你的小提琴的更新。

注意:我在这里使用了一个自执行函数,以便可以将样式表保存到局部变量中。我不想每次调用该方法时都创建一个新的样式表。只是第一次。

除非我误解了问题,否则您可以使用直接子选择器。

$('p > strong').css('color', 'turquoise');
这会将

样式标签附加到头部,然后将样式写入其中。然后,您没有内联样式。

(function($) {
   var styles = [];
   function styler(style){
      styles.push(style);
      $("#styler").html(styles.join("'n"));
   }
   $('button').on('click', function() {
      styler("p strong {color: turquoise;}")
   });
  $("head").append("<style id='styler'></style>")
})(jQuery);

:nth-child尝试过这个选择器.?
这是一个例子
https://jsfiddle.net/3pc98j7u/1/