javascript - 从背景大小 :cover/contain 中检索计算值

标签 javascript css

使用 background-size:cover 用 400x200 的背景图像覆盖浏览器的视口(viewport):

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

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

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

注意:我只是想阅读,而不是计算它(因为浏览器在某种程度上已经有了)

最佳答案

我知道我来晚了,但我已经使用下面的代码解决了这个问题。

    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);
    };

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

关于javascript - 从背景大小 :cover/contain 中检索计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216408/

相关文章:

javascript循环遍历字段,添加值并显示在另一个字段上

html - 使用 Twitter Bootstrap 连续 4 列

javascript - 使用 data-slide-to 和 javascript 将类添加到轮播导航

php - 内联 CSS 显示/隐藏 div 不起作用

javascript - 是否有任何 native 方法可以对浏览器中公开的点的有序列表进行三 Angular 测量?

javascript - Internet Explorer 8 按下按钮之间的延迟

javascript - Angular ng-repeat 有效...但没有绑定(bind)/显示任何值(Twig)

css - 显示/隐藏 DIV 不起作用 - 仅限 HTML/CSS

css - 具有不同轮廓重量的图标 - 是否可以调整?

javascript - 为什么OnMouseDown事件只发生一次,如何处理鼠标按住事件