【问题标题】:CSS - Background Size Contain or normalCSS - 背景大小包含或正常
【发布时间】:2016-10-04 15:33:50
【问题描述】:

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

有没有办法做到这一点?从长远来看,我无法控制图像,因为它是一个 WordPress 网站(所以图像必然会更改,无需程序员通过)

【问题讨论】:

  • 用JS根据宽度改变背景尺寸怎么样?
  • 不要以为你可以用 JS 获取背景中使用的图像的大小。如果可以,想知道怎么做。

标签: css background-image background-size


【解决方案1】:

  window.onload = function() {

    var imageSrc = document
                    .getElementsByClassName('foo')
                     .style
                      .backgroundImage
                       .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
                        .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"; 
      
    }

}

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多