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

前端 未结 6 1006
渐次进展
渐次进展 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:54

    Use below code this might help you to get background size after contain

    function get(img){
    
        var imageSrc = $(img).css('backgroundImage')
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                        .split(',')[0];    
        var image = new Image();
        image.src = imageSrc;
        var bgwidth = image.width,
        bgheight = image.height,    
        bgContainWidth = $(img).width();
    
        var bgContainHeight = (bgheight*bgContainWidth)/bgwidth;
    
        var decimal = bgContainHeight.toString().split('.');
    
        if(decimal[0]>=5)
        {
           bgContainHeight = Math.ceil(bgContainHeight);
        }
        else
        {
           bgContainHeight = Math.floor(bgContainHeight);
        }
    
        alert('bg Contain width = ' + bgContainWidth
               + ',bg Contain Height = ' + bgContainHeight);
    
    }
    
    $('#get').click(function () {
       get('#img');
    });
    

    See demo fiddle : http://jsfiddle.net/c4yHf/1/

提交回复
热议问题