简体   繁体   English

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

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

I have a script setup that detects whether an image is portrait or landscape. 我有一个脚本设置,可以检测图像是纵向还是横向。 In this case the image is landscape. 在这种情况下,图像是风景。 What I want to do is crop and center the image using absolute positioning, setting the height to 100% and giving it a negative margin-left based on half the image's width. 我想要做的是使用绝对定位裁剪和居中图像,将高度设置为100%并根据图像宽度的一半给予负边距。

I was able to do the above but here's the the problem I'm running into: The images I'm using all have variable widths/heights due to each of them being called from an API (in this case the Spotify API). 我能够做到以上但是这里遇到的问题是:我正在使用的图像都具有可变的宽度/高度,因为它们都是从API调用的(在本例中是Spotify API)。 That being said I had to use some Javascript to find their correct width. 话虽如此,我必须使用一些Javascript来找到正确的宽度。 Its doing just that but only before I add the class landscape , so in actuality its dividing the image width before being resized to fit in the 250px x 250px #container div using the css from that class. 它正是这样做的,但只有在我添加类landscape实际上,故其将图像的宽度调整大小以适应250像素X 250像素的前#container使用从类的CSS股利。

What I want it to do is divide the image's width after after its been resized using the properties from the landscape class. 我希望它做的是使用从属性的大小后后,将图像的宽度landscape类。

HTML HTML

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

CSS CSS

#container {height: 250px; width: 250px; overflow: hidden; position: relative;}

.landscape {position: absolute; height: 100%; left: 50%;}

.portrait {width: 100%;}

JS 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');
    }
});

You should refetch the width after you applied the class. 应用该类后,您应该重新获取宽度。 In your example you're using a cached width from before you actually applied the class. 在您的示例中,您在实际应用类之前使用了缓存宽度。 Working code: 工作代码:

$(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/ http://jsfiddle.net/d3u9tc0g/

Instead of using the value saved in $imgWidth , you need to recalculate it after the class is added. 而不是使用$imgWidth保存的值,您需要在添加类后重新计算它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM