代码之家  ›  专栏  ›  技术社区  ›  john

如何在找到div后在javascript/jquery中设置img标记的样式?

  •  1
  • john  · 技术社区  · 5 年前

    我正在一个wordpress/php网站上工作,在javascript/jquery中找到div后,我想在其中设置img标记的样式。

    需要执行以下操作的HTML代码:

    <div class="page-hero page-hero--reports cf">
       <figure class="page-hero__image img-fit" itemprop="image" itemscope="" itemtype="http://schema.org/ImageObject">
          <img src="">       // where opacity:0.7 needs to be apllied.  
       </figure>
       <div class="page-hero__content-contain">
          <h2 class="page-hero__title-top page-hero__title--heavy">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h2>
          <h2 class="page-hero__title-bottom page-hero__title--heavy"> More Coverage</h2>
       </div>
    </div>
    

    这是我试过的,但没用。

    $(".page-hero--reports").each(function () {
        if ($(this).find(".page-hero__title-top").not(":empty").length > 0 && $(this).find(".page-hero__title-bottom").not(":empty").length > 0) {
            $(this).find(".img-fit img").css("opacity", "0.7");
        } 
    });
    

    问题陈述:

    我想知道我需要在上面的脚本中做什么更改,以便在页面加载时在img标记上应用样式。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Jonathan    5 年前

    你用的是什么原因 .each ?

    // find elements
    $(".page-hero--reports img").css("opacity", "0.2");
    

    就像这样:

    // find elements
    $(".page-hero--reports img").css("opacity", "0.2");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="page-hero page-hero--reports cf">
       <figure class="page-hero__image img-fit" itemprop="image" itemscope="" itemtype="http://schema.org/ImageObject">
          <img src="https://cdn.cnn.com/cnnnext/dam/assets/190311171619-sarah-sanders-0311-medium-tease.jpg">
       </figure>
       <div class="page-hero__content-contain">
          <h2 class="page-hero__title-top page-hero__title--heavy">Trans Mountain Pipeline: NEB Releases New Report, Recommends Approval </h2>
          <h2 class="page-hero__title-bottom page-hero__title--heavy"> More Coverage</h2>
       </div>
    </div>