【问题标题】:jQuery .css not working for p and p.classjQuery .css 不适用于 p 和 p.class
【发布时间】:2012-09-07 21:09:25
【问题描述】:

我有一个 jQuery 函数,可以重新调整页面中许多元素的字体大小和行高,包括 p 和 p.latest_news。 除 p.latest_news 外,该函数与所有其他元素均按预期工作

应用于 p.latest_news 的 font-size 和 line-height 等于 p no 类(即 $('p').css({...

jQuery.1.7.1

代码

    $('p.article_news').css({
            'font-size' : Math.max(11,(.9 * newFontSize)),
            'line-height' : Math.max(13,(1.1 * newFontSize))+'px'
            });
    $('p').css({
            'font-size' : Math.max(14,newFontSize),
            'line-height' : Math.max(21,(1.7 * newFontSize))+'px'
            });

如果我只使用

    $('p.article_news').css({
            'font-size' : Math.max(11,(.9 * newFontSize)),
            'line-height' : Math.max(13,(1.1 * newFontSize))+'px'
            });

p.article_news 字体大小和行高按预期变化

为什么会这样? 如何影响每个 p、class 和 classless?

谢谢

【问题讨论】:

    标签: jquery css class


    【解决方案1】:

    您正在设置 article_news 字体大小,然后使用您的第二个选择器再次更改它。

    你需要的是:

    $('p.article_news').css({
            'font-size' : Math.max(11,(.9 * newFontSize)),
            'line-height' : Math.max(13,(1.1 * newFontSize))+'px'
            });
    $('p:not(.article_news)').css({
            'font-size' : Math.max(14,newFontSize),
            'line-height' : Math.max(21,(1.7 * newFontSize))+'px'
            });
    

    :not() 选择器基本上是选择所有不具有类 .active_news 的 p 节点。

    【讨论】:

    • 谢谢!!!收集知识的问题...对于我有多个 p.class 的情况,语法是什么? (即 $('p:not(.one_class), p:not(.another_class)') 或 $('p:not(.one_class)', 'p:not(.another_class)')或你能告诉我?
    • 我相信逗号分隔值应该可以工作。 :not(.classone, .classtwo) 等。这里是 :not() api.jquery.com/not-selector987654321@ 的 api 文档的链接
    【解决方案2】:

    只需翻转您的功能。首先使用带有 p 选择器的函数,然后使用带有 p.article_news 选择器的函数。

    您的 p 选择器函数正在覆盖 p.article_news 选择器函数。

    【讨论】:

      【解决方案3】:

      我喜欢马克的解决方案。

      但是如果两个函数一起调用,你可以翻转它们并让它们工作。

      $('p').css({
                  'font-size' : Math.max(14,newFontSize),
                  'line-height' : Math.max(21,(1.7 * newFontSize))+'px'
                  });
      $('p.article_news').css({
                  'font-size' : Math.max(11,(.9 * newFontSize)),
                  'line-height' : Math.max(13,(1.1 * newFontSize))+'px'
                  });
      

      可能比使用:not检查更快

      【讨论】:

        【解决方案4】:

        当您设置p 样式时,您将覆盖您在p.article_news 中添加的样式,因为所有p.article_news 都是p。您可以先设置p 的样式,然后再设置p.article_news,也可以使用p:not(.article_news) 代替p

        【讨论】:

          猜你喜欢
          • 2011-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-23
          • 2018-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多