获取背景图片的最终尺寸 [英] Get final size of background image

查看:137
本文介绍了获取背景图片的最终尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个简单的方法来获取背景图像的最后的高度和宽度使用Javascript或jQuery,即使应用 background-size 属性吗?



我的意思是,我知道我可以得到背景图像url并将其加载到 Image 对象,然后获取宽度和高度。但它是源图像的大小。如果有人用CSS缩放它,然后尺寸改变



如何找到它的最终尺寸?



@edit



它不同于标记为相似的问题,因为它没有说如何获得像素的大小,如果有人改变了 background-size

解决方案

使用 getComputedStyle ,我创建了这个脚本,返回给定元素的背景宽度和高度,以像素为单位。它适用于:




  • 尺寸(宽度或高度)设置为自动 auto

  • 尺寸设置为百分比

  • 尺寸设置为像素 px

  • 将尺寸设置为任意之前的组合。 ( ie width:100px; height:auto width:auto; height:32.4 % height:100px; width:2% code>)

  • background-size 设为 c>或包含



$ c> background-size 是使用外部CSS文件内嵌CSS 内联标题CSS em> (意思是宽度和高度都是 auto )。



这是一个JsFiddle(带封面示例)



http ://jsfiddle.net/gp4e9d3z/3/



这里是StackOverflow的代码片段( code> units)



  function getBackgroundSize(elem){// This:// *获取elem计算样式: //  -  CSS background-size //  - 元素的宽度和高度// *提取背景URL var computedStyle = getComputedStyle(elem),image = new Image(),src = computedStyle.backgroundImage.replace(/ url\(([ ')])?(。*?)\1\)/ gi,'$ 2'),cssSize = computedStyle.backgroundSize,elemW = parseInt(computedStyle.width.replace('px',' ,elemH = parseInt(computedStyle.height.replace('px',''),10),elemDim = [elemW,elemH],calculatedDim = [] //使用提取的网址加载图片。 //应该在缓存中。 image.src = src; //确定'ratio'ratio = image.width> image.height? image.width / image.height:image.height / image.width; //将背景大小属性拆分为数组cssSize = cssSize.split(''); //第一个属性是width。它总是设置为某物。 computedDim [0] = cssSize [0]; //如果height未设置,请将其设置为auto computedDim [1] = cssSize.length> 1? cssSize [1]:'auto';如果(elemDim [0]> elemDim [1]){// Elem's ratio大于或等于img ratio if(elemDim [0] 0] / elemDim [1]> = ratio){calculatedDim [0] = elemDim [0]; computedDim [1] ='auto'; } else {calculatedDim [0] ='auto'; computedDim [1] = elemDim [1]; }} else {computedDim [0] ='auto'; computedDim [1] = elemDim [1];如果(elemDim [0]< elemDim [1]){computedDim [0] = elemDim [0];}} else if(cssSize [0] ===' computedDim [1] ='auto'; } else {// elem的比率大于或等于img ratio if(elemDim [0] / elemDim [1]> = ratio){computedDim [0] ='auto'; computedDim [1] = elemDim [1]; } else {calculatedDim [1] ='auto'; computedDim [0] = elemDim [0]; }}} else {//如果不是覆盖或包含,循环遍历值(var i = cssSize.length; i--;){//检查值是以像素还是以百分比if(cssSize [i] .indexOf('px')> -1){//如果以像素为单位,只需删除'px',得到computedDim [i] = cssSize [i] .replace('px',' ); } else if(cssSize [i] .indexOf('%')> -1){//如果百分比,获得elem尺寸的百分比//并将其赋给计算尺寸computedDim [i] = elemDim [i] * (cssSize [i] .replace('%','')/ 100);如果两个值都设置为auto,则返回图像的//原始宽度和高度if(computedDim [0] ==='auto'&& amp; calculatedDim [1] ==='auto'){computedDim [0] = image.width; computedDim [1] = image.height; } else {//根据宽度或高度是否为auto,//计算auto的值(以像素为单位)。 // ratio在这里只是得到比例。 ratio = computedDim [0] ==='auto'? image.height / computedDim [1]:image.width / calculatedDim [0]; computedDim [0] = calculatedDim [0] ==='auto'? image.width / ratio:calculatedDim [0]; computedDim [1] = calculatedDim [1] ==='auto'? image.height / ratio:calculatedDim [1]; } //最后,返回一个具有//背景图像的宽度和高度的对象。 return {width:computedDim [0],height:computedDim [1]};} //调试功能的东西updateData(){var background = getBackgroundSize(document.body); document.getElementById('width')。innerHTML = background.width +'px'; document.getElementById('height')。innerHTML = background.height +'px'; document.getElementById('winWidth')。innerHTML = getComputedStyle(document.body).width; document.getElementById('winHeight')。innerHTML = getComputedStyle(document.body).height;} //执行onload,以便背景图片已经加载.window.onload = window.onresize = updateData;  

  html,body {width:100%;高度:100%; margin:0; padding:0;} body {background:url('http://hdwallpapersfit.com/wp-content/uploads/2015/03/images-7.jpg'); background-size:80%auto;} div {background:rgba(0,0,0,0.5); color:#fff;}  

 < div id = data>背景宽度:< span id =width>< / span> < br>背景高度:< span id =height>< / span> < hr>正文宽度:< span id =winWidth>< / span> < br>身高:< span id =winHeight>< / span>< / div>  

b $ b

is there an easy way to get the final height and width of a background image with Javascript or jQuery even if a background-size property was applied?

I mean, I know I can get the background image url and load it to an Image object and then get the width and height. But it is the size of the source image. If someone scaled it with CSS then the size changed

How can I find its final size?

@edit

it is different from the question marked as similar because it doesnt say how to get the size in pixels if someone changed the background-size

解决方案

Using getComputedStyle, I've created this script that returns the width and height of a given element's background, in pixels. It works with:

  • Dimensions (width or height) set to auto, either explicitly or because no specific value was given (width and height default to auto)
  • Dimensions set to percentage %
  • Dimensions set to pixels px
  • Dimensions set to a combination of any of the previous. (i.e width: 100px; height: auto or width: auto; height: 32.4% or height: 100px; width: 2% or width: 21.2%)
  • background-size set to cover or contain

It works if background-size is set with an external CSS file, inline CSS, inline header CSS or if it is not set at all (meaning width and height are auto).

Here's a JsFiddle (with cover example)

http://jsfiddle.net/gp4e9d3z/3/

And here's StackOverflow's code snippet (with percentage auto units)

function getBackgroundSize(elem) {
    // This:
    //       * Gets elem computed styles:
    //             - CSS background-size
    //             - element's width and height
    //       * Extracts background URL
    var computedStyle = getComputedStyle(elem),
        image = new Image(),
        src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2'),
        cssSize = computedStyle.backgroundSize,
        elemW = parseInt(computedStyle.width.replace('px', ''), 10),
        elemH = parseInt(computedStyle.height.replace('px', ''), 10),
        elemDim = [elemW, elemH],
        computedDim = [],
        ratio;
    // Load the image with the extracted URL.
    // Should be in cache already.
    image.src = src;
    // Determine the 'ratio'
    ratio = image.width > image.height ? image.width / image.height : image.height / image.width;
    // Split background-size properties into array
    cssSize = cssSize.split(' ');
    // First property is width. It is always set to something.
    computedDim[0] = cssSize[0];
    // If height not set, set it to auto
    computedDim[1] = cssSize.length > 1 ? cssSize[1] : 'auto';
    if(cssSize[0] === 'cover') {
        // Width is greater than height
        if(elemDim[0] > elemDim[1]) {
            // Elem's ratio greater than or equal to img ratio
            if(elemDim[0] / elemDim[1] >= ratio) {
                computedDim[0] = elemDim[0];
                computedDim[1] = 'auto';
            } else {
                computedDim[0] = 'auto';
                computedDim[1] = elemDim[1];
            }
        } else {
            computedDim[0] = 'auto';
            computedDim[1] = elemDim[1];
        }
    } else if(cssSize[0] === 'contain') {
        // Width is less than height
        if(elemDim[0] < elemDim[1]) {
            computedDim[0] = elemDim[0];
            computedDim[1] = 'auto';
        } else {
            // elem's ratio is greater than or equal to img ratio
            if(elemDim[0] / elemDim[1] >= ratio) {
                computedDim[0] = 'auto';
                computedDim[1] = elemDim[1];
            } else {
                computedDim[1] = 'auto';
                computedDim[0] = elemDim[0];
            }
        }
    } else {
        // If not 'cover' or 'contain', loop through the values
        for(var i = cssSize.length; i--;) {
            // Check if values are in pixels or in percentage
            if (cssSize[i].indexOf('px') > -1) {
                // If in pixels, just remove the 'px' to get the value
                computedDim[i] = cssSize[i].replace('px', '');
            } else if (cssSize[i].indexOf('%') > -1) {
                // If percentage, get percentage of elem's dimension
                // and assign it to the computed dimension
                computedDim[i] = elemDim[i] * (cssSize[i].replace('%', '') / 100);
            }
        }
    }
    // If both values are set to auto, return image's 
    // original width and height
    if(computedDim[0] === 'auto' && computedDim[1] === 'auto') {
        computedDim[0] = image.width;
        computedDim[1] = image.height;
    } else {
        // Depending on whether width or height is auto,
        // calculate the value in pixels of auto.
        // ratio in here is just getting proportions.
        ratio = computedDim[0] === 'auto' ? image.height / computedDim[1] : image.width / computedDim[0];
        computedDim[0] = computedDim[0] === 'auto' ? image.width / ratio : computedDim[0];
        computedDim[1] = computedDim[1] === 'auto' ? image.height / ratio : computedDim[1];
    }
    // Finally, return an object with the width and height of the
    // background image.
    return {
        width: computedDim[0],
        height: computedDim[1]
    };
}

// Stuff for debugging

function updateData() {
    var background = getBackgroundSize(document.body);
    document.getElementById('width').innerHTML = background.width + 'px';
    document.getElementById('height').innerHTML = background.height + 'px';
    document.getElementById('winWidth').innerHTML = getComputedStyle(document.body).width;
    document.getElementById('winHeight').innerHTML = getComputedStyle(document.body).height;
}
// Execute onload, so that the background image is already loaded.
window.onload = window.onresize = updateData;

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
body {
    background: url('http://hdwallpapersfit.com/wp-content/uploads/2015/03/images-7.jpg');
    background-size: 80% auto;
}
div {
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
}

<div id="data">
    Background width: <span id="width"></span>
    <br>
    Background height: <span id="height"></span>
    <hr>
    Body width: <span id="winWidth"></span>
    <br>
    Body height: <span id="winHeight"></span>
</div>

这篇关于获取背景图片的最终尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆