查找图像's通过Javascript添加CSS类后的宽度

Finding an Image's Width After Adding a CSS Class via Javascript

本文关键字:CSS 添加 Javascript 图像 通过 查找      更新时间:2023-09-26

我有一个脚本设置,可以检测图像是纵向还是横向。在这种情况下,图像是横向的。我想做的是使用绝对定位裁剪和居中图像,将高度设置为100%,并根据图像宽度的一半为其留出负边距。

我能够做到以上几点,但我遇到的问题是:我使用的图像都有不同的宽度/高度,因为每个图像都是从API(在本例中是Spotify API)调用的。话虽如此,我不得不使用一些Javascript来找到它们的正确宽度。它只是这样做,但只是在我添加类landscape之前,所以实际上它在调整大小以适应250px x 250px #containerdiv之前,使用该类的css来划分图像宽度。

我希望它使用landscape类的属性在调整图像大小后,在之后划分图像的宽度。

HTML

<div id="container">
  <img src="https://i.scdn.co/image/9c4880556288e2f4d098a104f5125e477611be32" >
</div>

CSS

#container {height: 250px; width: 250px; overflow: hidden; position: relative;}
.landscape {position: absolute; height: 100%; left: 50%;}
.portrait {width: 100%;}

JS

$(function() {
    var $img       = $('img'),
        $imgHeight = $img.height(),
        $imgWidth  = $img.width();  
    if ($imgWidth > $imgHeight) {
        $img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $imgWidth / 2 + 'px',
            });
    } else {
        $img.addClass('portrait');
    }
});

您应该在应用类之后重新蚀刻宽度。在您的示例中,在实际应用类之前,您使用了中的缓存宽度。工作代码:

$(function() {
    var $img       = $('img'),
        $imgHeight = $img.height(),
        $imgWidth  = $img.width();  
    if ($imgWidth > $imgHeight) {
        $img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $img.width() / 2 + 'px',
            })
    } else {
        $img.addClass('portrait');
    }
});

http://jsfiddle.net/d3u9tc0g/

您不需要使用保存在$imgWidth中的值,而是需要在添加类后重新计算它。

$img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $img.width() / 2 + 'px',
            });