如何在jquery中仅将css更改应用于此对象

时间:2017-08-25 17:57:30

标签: jquery css

此代码在将自定义阴影的大小调整为图像高度方面效果很好。但是如果我将它应用于页面上不同大小的图像,它会将所有图像调整为第一个图像大小。如何使其更具体?消隐语法。

  <li class="col third impact-home">         
      <div class="image-with-overlay">
        <%= image_tag 'impact.jpg', :class => "image-with-shadow" %>
        <div class="image-shadow"></div>
      </div>
  </li>   

$(document).ready( function() { //Fires when DOM is loaded
    getImageSizes();
    $(window).resize(function() { //Fires when window is resized
        getImageSizes();
    });
});

function getImageSizes() {
    var imgHeight = $(".image-with-shadow").height();
    var imgMargin = (- imgHeight) * .995;
    console.log(imgMargin);
    $(".image-shadow").css({"height": imgHeight});
    $(".image-shadow").css({"margin-top": imgMargin});
}

1 个答案:

答案 0 :(得分:1)

您需要遍历每个图像并单独处理它们。没有HTML我不知道.image-shadow如何与图像本身相关但它可能看起来像这样

function getImageSizes() {
        $(".image-with-shadow").each(function () {
            var imgHeight = $(this).height();
            var imgMargin = (- imgHeight) * .995;
           console.log(imgMargin);
           //need to select the image shadow in relation to each image
           //with no HTML reference i'm not sure how it's laid out
           $(this).closest(".image-shadow").css({"height": imgHeight});
           $(this).closest(".image-shadow").css({"margin-top": imgMargin});
    })

}