Get the size of background-image with jQuery after containing with CSS

前端 未结 6 898
渐次进展
渐次进展 2021-01-22 00:16
#img {
    width:300px;
    height:300px;
    overflow:hidden;
    background-repeat: no-repeat !important;
    background-position: center !important;
    background-si         


        
6条回答
  •  花落未央
    2021-01-22 00:49

    I think the flaw with this plan is that the background-image isn't really part of the DOM when the page is loaded. When you query .css('background-size') you'll return the CSS rule value (i.e. key:value) that is assigned to that rule's key.

    So if i have a div with a background of #000 and i ask jQuery to return $('div').css('background') it'll return the value of #000.

    Since you're using the container to scale a background image, to squeeze it to new dimensions, your value for .css('background-size') will never be a computed value like "100px 500px". It will probably be "auto". Also, the property of background-size doesn't have an attribute of width so .css('background-size').width() won't return a value in the jQuery you have above.

    The only solution I can think of is to use JS to find the initial dimensions of the image, then the final dimensions of it's container after the page renders, and compute the ratio between the two using math and if-else statements.

    Example:

    IMG original dimensions: 1000px x 400px
    container's dimensions after page renders: 600px x 200px
    
    // Compare the ratio of height / height and width / width
    widthRatio = .6
    heightRatio = .5
    
    // image should scale proportionally, so it must scale to the smallest ratio
    // e.g. if it needs to be 50% as tall, it has to be 50% as wide, even though
    // it could fit set at 60% its original width
    
    // so multiply ratio (.5) by original dimensions of image (1000px x 400px)
    newImgBgDimensions = 500px x 200px
    

提交回复
热议问题