【问题标题】:How can I add a css rule to a dynamically created element in jquery如何将css规则添加到jquery中动态创建的元素
【发布时间】:2019-12-13 05:25:13
【问题描述】:

是否可以在 jquery 中将 css 添加到特定的动态创建的 div 中?我想向特定的 div 添加叠加层,但试图找到一种方法将 id 从动态创建的 div 传递到 jquery 函数,以便仅将 CSS 规则添加到该特定的 div,这对我来说是一项任务。当我单击 div 时,它会将叠加层添加到所有这些中。 感谢您的宝贵时间,这是我的代码。

foreach($selectedPhotoResult as $rowSelect){
    if($counter % 3 === 1){
        echo '</div><div class="row">';
    }
        echo'
        <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
            <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'"><div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a>
                <div class="well photoControlsMain pht-brd-cl">
                    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
                        <div class="imageOverlayStyle">
                            Something here
                        </div>
                        <figure>                                                        
                           <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt=""/>

                        <div class="photoControlsMainImage">
                            <p style="z-index:9999;">
                        <span class="text-prt-und-bl usernameIndexPos">'.ucwords($row['industryName']).'</span>
                        <span class="adRateIndexPos">$'.$row['ad_rate'].'/hr</span>
         ';

    if($userfile->member_is_loggedin()){    
        echo'<a class="userMsgID" data-toggle="modal" data-target="#msgUserModal" data-userSenduserID-id="'.$rowSelect['user_id'].'" data-userSend-id="'.$rowSelect['industryName'].'" data-username-modal="'.ucwords($rowSelect['industryName']).'"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>';
            if($favList->rowCount() > 0){                                           
                foreach($favListResult as $rowFav){
                    if($rowFav['user_fav_id'] == $user_id){
                            echo'<span class="heartIcoPosRed adUnFav" data-unfav-id="'.$rowFav['fav_id'].'"><a><i class="fa fa-heart heartIcoRedColor"></i></a></span></a>';
                            }                                       
                    }   
            }else{
                echo'<span class="heartIcoPos adFav" data-userFav-id="'.$user_id.'" data-fav-id="'.$row['ad_id'].'"><a class="heartIcoWhite"><i class="fa fa-heart"></i></a></span></a>';
            }   
                echo city($row['ad_city']);
        }else{                                          
            echo'</a>
                <a class="loginDisplayHeader" style="display:none;"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="commentIcoPos"><i class="fa fa-comment-o"></i></span></a>
                <a class="loginDisplayHeader" style="display:none;"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                <a class="loginDisplayHeaderFull" id="loginFormShowHeader"><span class="heartIcoPos heartIcoWhite"><i class="fa fa-heart"></i></span></a>
                ';

                echo city($row['ad_city']);
                }

            $likes = $conn->prepare("SELECT count(likes) as likeCount
                FROM 
                    likes
                WHERE
                    user_accept_id = :adUserId                                  
                ");
                $likes->bindParam(":adUserId", $adUserId);
                $likes->execute();
                $likesFetch = $likes->fetchAll();                                       
                if($likes->rowCount() > 0){
                    foreach($likesFetch as $rowLikes){

                        echo'<span class="userLikeBtnLG">'.thousandsCurrencyFormat($rowLikes['likeCount']).' Likes <i class="fa fa fa-thumbs-o-up thbsUPND"></i></span>';

                            }
                        }
                    echo'</p>
            </div>
        </figure>
    </div>
 </div>                                             
 '; 
}

这是到目前为止的 jquery 代码

   $(".overlayPicHL").on("click", function() {
     const imageOverlayStyle = 
     $(this.nextElementSibling).find('.imageOverlayStyle');
     $(imageOverlayStyle).css({
     backgroundColor: 'yellow'
     });
   });

这是覆盖项的 CSS

.imageOverlayStyle {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #008CBA;
  overflow: hidden;
  width: 100%;
  height: 0;
  transition: .5s ease;
}

这是一个简单的叠加过渡,我只需要弄清楚如何将此叠加添加到从数据库中提取的特定 div 中......动态创建。我已经搜索了一段时间的解决方案,但还没有这样的运气。

【问题讨论】:

  • 使用事件委托作为$(document).on("click", "selector", function() {...});
  • 感谢@DevsiOdedra 的帮助,我尝试了你的方式,但由于某种原因它不想在我的末端开火。如果我只使用 $(".imageOverlayStyle").css({"height":"100%"});然后它会显示在所有这些上,但是如果我使用您的 $(this).next 解决方案,它不会触发 css 规则
  • 所以试试$(this).next().css..它会工作
  • 是的,由于某种原因 this.next 不想工作。 :( 当我删除 $(this).next 并且只有我的原始代码 $(".imageOverlayStyle").css({"height":"100%"}); 然后它会在所有动态图像上触发图像叠加图片,但是当我使用 $(this).next 时没有任何反应。:(

标签: php jquery css


【解决方案1】:

您要定位的.imageOverlayStyle 是单击的.overlayPicHL 的下一个兄弟的子级,因此请使用nextElementSibling[0]

$(".overlayPicHL").on("click", function() {
  const imageOverlayStyle = $(this.nextElementSibling).find('.imageOverlayStyle');
  $(imageOverlayStyle).css({
    backgroundColor: 'yellow'
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
  <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL
    <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div>
  </a>
  <div class="well photoControlsMain pht-brd-cl">
    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
      <div class="imageOverlayStyle">
        Something here
      </div>
      <figure>
        <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" />

        <div class="photoControlsMainImage">
          <p style="z-index:9999;">
            <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span>
            <span class="adRateIndexPos">adrate</span>
          </p>
        </div>
      </figure>
    </a>
  </div>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer">
  <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">overlayPicHL
    <div class="price"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div>
  </a>
  <div class="well photoControlsMain pht-brd-cl">
    <a class="mainImageProfile" style="display:block;" data-userMain-id="'.$row['ad_user'].'" data-pic-id="'.$row['ad_photo_thumb'].'">
      <div class="imageOverlayStyle">
        Something here
      </div>
      <figure>
        <img src="'.$row['ad_photo_thumb'].'" class="img-responsive imageSizingGallery imageProfileStyleSmall" style="object-fit: contain;" width="100%" alt="" />

        <div class="photoControlsMainImage">
          <p style="z-index:9999;">
            <span class="text-prt-und-bl usernameIndexPos">usernameIndexPos</span>
            <span class="adRateIndexPos">adrate</span>
          </p>
        </div>
      </figure>
    </a>
  </div>
</div>

【讨论】:

  • 感谢@CertainPerformance 的解决方案,我尝试了您的解决方案,但它没有添加css 规则。当我使用 $(".imageOverlayStyle").css({"height":"100%"});它将样式添加到所有元素,但是当我添加您的代码时,什么都不会显示。 :(
  • sn-p 中的backgroundColor: yellow 只是一个示例,表明代码按预期工作。当然,您必须更改它以使用您想要的实际 CSS。
  • 我尝试使用我的 css({"height":"100%"}) 运行您的代码,但仍然不会显示覆盖。当我运行我的原始代码时,它会将 css 添加到所有动态显示的图像中。会不会有其他原因导致它不会将 css 规则添加到特定的 div 中?
  • 任何控制台错误?正如您在现场 sn-p 中看到的那样,鉴于问题中提供的 HTML,答案中的代码似乎正在运行。如果它不适合您,听起来问题中给出的 HTML 不是您的 actual HTML 结构?
  • 是的,我看到您的代码在代码 sn-p 中触发时添加了正确的样式,但是当我在我的环境中运行它时,它不会触发 css 规则并显示覆盖任何 div。我用我正在使用的更多内容更新了我的代码。谢谢
【解决方案2】:

将规则添加到样式表中,以便它们自动应用于新创建的元素。 创建元素时链接 css() 方法: $('') 。追加到(文件. ... 动态创建新样式表:$("")。

$('<img id="newImage" src="text.jpg"/>')
.appendTo(document.body)
.css(style);

动态创建新样式表:

$("<style>").text("#myNewEl { width:40px; height:35px; }").appendTo("head");

【讨论】:

    【解决方案3】:

    您可以在整个文档中找到class并添加css,如果您希望它只添加到next()div中,您可以使用next()

    $(document).on("click", ".overlayPicHL", function(){
        var id = $(this).attr("data-overlayPicID-id");
        $(this).next(".imageOverlayStyle").css({"height":"100%"}); //<-this is the css I want to add to the specific div when the icon has been clicked
    });
    .imageOverlayStyle {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: #008CBA;
      overflow: hidden;
      width: 100%;
      height: 0;
      transition: .5s ease;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <a class="overlayPicHL" data-overlayPicID-id="'.$row['ad_id'].'">
    
    <div class="price" style="position:absolute;top:0px;;right:15px;z-index:98;height:50px;width:50px;border-radius: 0px 5px 0px 0px;background-image: linear-gradient(to bottom, rgba(0,0,0,0.8) 50%, rgba(0,0,0,0) 100%);"><i class="fa fa-eye" style="font-size:25px;color:#ffffff;position:absolute;top:10px;right:10px;"></i></div></a>
    <div class="imageOverlayStyle" id="imgOvrlayID" data-imgOvly-id="'.$row['ad_id'].'">
        Something here
    </div>

    【讨论】:

    • @Stuckfornow 你能在有多个博客和 div 的地方发布 html
    • 我添加了更多代码,让您更深入地了解可能发生的情况。感谢您的宝贵时间。
    • 是的,但它不完整,只需添加完整的 div,如 start &lt;div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 text-center picContainer"&gt; 和该 div 的末尾
    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2014-03-28
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多