CSS - 背景大小包含或正常

CSS - Background Size Contain or normal

如果背景图像大于 div (background-size:contain;) 并且图像较小,我想找到一些方法将背景图像包含在 div 中比 div,保持原样,不要拉伸和模糊它 (background-size:auto;)

有什么办法吗?我无法控制长 运行 中的图像,因为它是一个 WordPress 网站(因此图像必然会更改,而无需经过程序员)

  window.onload = function() {

    var imageSrc = document
                    .getElementsByClassName('foo')
                     .style
                      .backgroundImage
                       .replace(/url\((['"])?(.*?)\)/gi, '')
                        .split(',')[0];

   
    var divWidth = imageSrc.offsetWidth;

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    alert('width =' + width + ', height = ' + height)
    
    if ( width > divWidth ) {
      
        imageSrc.style.backgroundSize = "contain"; 
      
    }

}