获取背景图片尺寸

时间:2015-09-29 23:53:07

标签: javascript jquery css background

我想让这个设计响应,我将需要使用javascript或JQuery的背景图像尺寸(宽度,高度)。任何想法?

<div class="container">
    <div id="result" class="result">&nbsp</div>
    <div class="slot-container">
            <div id="slot1" class="slot"></div>
            <div id="slot2" class="slot"></div>
            <div id="slot3" class="slot"></div>
        <div><button id="control" class="btn">START</button></div>
        <div id="try" class="result try">TRY 0</div>
    </div>

</div>

https://jsfiddle.net/h0fbha33/

2 个答案:

答案 0 :(得分:1)

$(window).on("load", function () {
    var img = new Image();
    img.src = $('.slot').css('background-image').replace(/.*\s?url\([\'\"]?/, '').replace(/[\'\"]?\).*/, '');
    alert( img.width + ' and ' + img.height);
});

以下是小提琴链接:https://jsfiddle.net/beroza/a01y1me4/

答案 1 :(得分:0)

您可以使用:

var img = new Image;
img.src = $('body').css('background-image').replace(/url\(|\)$/ig, "");
var bgImgWidth = img.width;
var bgImgHeight = img.height;