Get posX and posY of background-position in Javasc

2019-04-10 21:45发布

If I assume that the background position will always be in the format:

0px 0px; or 10px 11px; So, *number*px *number*px.

How can I get both the x position and the y position in Javascript?

1条回答
手持菜刀,她持情操
2楼-- · 2019-04-10 22:43

Given the following HTML:

<div id="demo"></div>

And CSS:

div {
    height: 500px;
    width: 500px;
    margin: 0 auto;
    background: #fff url(http://placekitten.com/300/300) 50% 50% no-repeat;
}

The following JavaScript works:

var demo = document.getElementById('demo'),
    _tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
    positions = {
        'left' : _tmp[0],
        'top' : _tmp[1]
    };
console.log(positions, positions.left, positions.top);

JS Fiddle demo.

The above approach does require a browser that supports window.getComputedStyle() (obviously), and trim() (though that could be replaced with a replace(/^\s+|\s+$/g,'')).

To get access to the units, and numbers, independently I'd suggest creating other objects within the overall object to hold those numbers, and units:

var demo = document.getElementById('demo'),
    _tmp = window.getComputedStyle(demo,null).backgroundPosition.trim().split(/\s+/),
    positions = {
        'left' : _tmp[0],
        'top' : _tmp[1],
        'numbers' : {
            'left' : parseFloat(_tmp[0]),
            'top' : parseFloat(_tmp[1])
        },
        'units' : {
            'left' : _tmp[0].replace(/\d+/,''),
            'top' : _tmp[1].replace(/\d+/,'')
        }
    };
console.log(positions, positions.left, positions.top, positions.numbers.left, positions.numbers.top, positions.units.left, positions.units.top);

JS Fiddle demo.

As to what would happen if there was no background-position set? Well, why not try that, with the following CSS:

div {
    height: 500px;
    width: 500px;
    margin: 0 auto;
    background-color: #fff;
    background-image: url(http://placekitten.com/300/300);
    background-repeat: no-repeat;
}

In Chromium it seems that you get the default background-position of 0% 0% (and corresponding numbers and units): JS Fiddle demo.

References:

查看更多
登录 后发表回答