开发者

Can you extract a background-size 'auto' value, using jquery, javascript, or css?

If I have

background-size: 50% auto;

What if I want to e开发者_StackOverflow中文版xtract the auto value, basically to be able to get the new height or width?


In CSS3, 'background-size' is relative to the container element. So, '50% auto' will always be exactly half of the width of it's container.

That said, you can get half of the width with jquery like so:

$(function() {
    var w = $('.yourcontainer').width() / 2;
    alert(w);
});

By specifying two values you are defining width and height... You have height set to 'auto', so your image will keep it's original proportions instead of scaling to 50% height. That makes it hard to get the 'height' value without knowing the original proportions of the image. Luckily, you can get those values into javascript pretty easily by creating a new DOM element and testing it's dimensions:

$(function() {

    var img = new Image();
    img.src = 'images/yourimage.jpg';

    var w = $('.yourcontainer').width() / 2;
    var h = (w / img.width) * img.height;

    alert(h);

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜