从background-size:cover/contains中检索计算值

abe*_*ier 31 javascript css css3

使用以下内容覆盖浏览器的视口,使用400x200背景图像background-size:cover:

html, body {height:100%;}
body {background:url("http://lorempixel.com/g/400/200/") center no-repeat; background-size:cover;}
Run Code Online (Sandbox Code Playgroud)

我想通过javascript检索background-size例如应用于图片的计算值1536px 768px

现场演示:http://s.codepen.io/abernier/fullpage/rHkEv

注意:我只是想读它,在任何时候都没有计算它(因为浏览器已经有了某种方式)

小智 10

我知道我参加晚会很晚,但我已经用下面的代码解决了这个问题.

    var backgroundImage = new Image();
    backgroundImage.src = $('my_div_id').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");

    backgroundImage.onload = function() {
        var width = this.width;
        var height = this.height;

        var object = $('#my_div_id');

        /* Step 1 - Get the ratio of the div + the image */
        var imageRatio = width/height;
        var coverRatio = object.outerWidth()/object.outerHeight();

        /* Step 2 - Work out which ratio is greater */
        if (imageRatio >= coverRatio) {
            /* The Height is our constant */
            var coverHeight = object.outerHeight();
            var scale = (coverHeight / height);
            var coverWidth = width * scale;
        } else {
            /* The Width is our constant */
            var coverWidth = object.outerWidth();
            var scale = (coverWidth / width);
            var coverHeight = height * scale;
        }
        var cover = coverWidth + 'px ' + coverHeight + 'px';
        alert('scale: ' + scale + ', width: ' + coverWidth + ', height: ' + coverHeight + ', cover property: ' + cover);
    };
Run Code Online (Sandbox Code Playgroud)

详细的演练可以在这里找到http://www.gene.co.uk/get-computed-dimensions-background-image-background-size-cover/


mix*_*ure 5

您可以使用Image对象获取背景图像文件的尺寸,然后将其与元素的大小进行比较

var element = ...

var img = new Image()
img.onload = compare;
img.src = 'path/to/your/background-image'

function compare() {
  var fx = element.offsetWidth/img.width;
  var fy = element.offsetHeight/img.height;
  console.log(fx, fy);
}
Run Code Online (Sandbox Code Playgroud)

然后,根据background-size属性的值,您可以获得精确的比例因子

function compare() {
  var fx = element.offsetWidth/img.width;
  var fy = element.offsetHeight/img.height;

  var bs = window.getComputedStyle(element, null).backgroundSize;
  switch (bs) {
    case 'cover': console.log(Math.min(fx, fy)); break;
    case 'contain': console.log(Math.max(fx, fy)); break;
    case '100% 100%': console.log(fx, fy);
    default: console.log("Umm...");
  }
}
Run Code Online (Sandbox Code Playgroud)

默认情况更复杂.由于背景大小的每个部分都可以以单位数量表示,因此正确处理这些单位的代码将会有点夸张和丑陋.

基于jQuery的小提琴


小智 0

您可以检查 div 和原始图像的大小,看看 div 的宽度或高度是否按比例变短,这意味着图像被拉伸到较小一侧的 100%。例如:如果容器 div 为 600px X 500px,图像大小为 600px X 400px,则图像将调整大小以覆盖整个 div,因此它将调整大小为 auto X 500px,这意味着图像的缩放将为 500/ 400 = 1.25

  • OP 特别表示他们不想自己计算比例因子,而是简单地通过 API 调用检索它。(如果存在的话。) (3认同)