开发者

Is it possible to measure the resulting background image when using background-size: cover with Javascript?

I want to know if it's possible to determine the (new) dimensions of a background image after it has been resized with css3's 'background-size: cover' using Javascript. (Not working) 开发者_高级运维Example: http://jsfiddle.net/daco/GygLJ/3/

Cheers,

  • Daco


I don't know enough pure JS to post this without assuming jQuery but it can probably be ported easily.

What you could do is find the src of the background image, then use javascript's built in width / height functions to get its dimensions.

eg:

    //jQuery
var imgSrc = $('#test').css('background-image');
//might need to do a bit of parsing on that, returns: url(http://blahblah)
alert(imgSrc);
imgSrc=imgSrc.replace('url("', '').replace('")', '');
alert(imgSrc);

var newImg = new Image();
newImg.onload=function()
{
    var h = newImg.height;
    var w = newImg.width;
    alert('w:'+w+' h:'+h);
};
newImg.src=imgSrc;

Hope this helps

Example here: http://jsfiddle.net/vap8p/

EDIT: updated source and linked to working example


Assuming background-image css for element with ID 'mydiv'. All native JavaScript. Won't interact with other JavaScript on page.

(function (id) {
    var img = new Image(), elm = document.getElementById(id);
    img.dataset.w = elm.offsetWidth;
    img.dataset.h = elm.offsetHeight;
    img.addEventListener('load', function () {
        var maxw = this.dataset.w,
            maxh = this.dataset.h,
            aspect = this.width / this.height;
        if(maxw > maxh * aspect) alert(maxw + ' x ' + maxw / aspect);
        else alert(maxh * aspect + ' x ' + maxh);
    }, false);
    img.src = window.getComputedStyle(elm).backgroundImage.slice(4, -1);
})('mydiv');​

You might want to round down.

For contain rather than cover, change the compare to the opposite.

if(maxw < maxh * aspect) alert(maxw + ' x ' + maxw / aspect);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜