开发者

Body background position must be relative to a page element

I've got a body background which must be relative to a page element (#container). When the page is resized (smaller width) the container moves to the left (because it's centered). The background should also be moving left with the same amount.

Now I've got the following code, which works for my problem:

/*
 * The background must be relative to the rest of the page elements.
 * The background position.left = 0px when the offset.left of the container = 362.
 * The new background position.left is based on the current position of the container.
 */
var beginBackgroundPositionLeft = 362;
function changeBackgroundPosition() {
    var newLeft = jQuery("div.container").offset().left;
    newLeft = (-1 * beginBackgroundPositionLeft + newLeft) + "px";
    jQuery("body").css("background-position", newLeft + " 0px");
}

jQuery(window).resize(function(e){
    console.log(e);
    // Change the position of the background 
    // when resizing the window.
    changeBackgroundPosition();
});

jQuery(doc开发者_开发知识库ument).ready(function() {

    // Change the position of the background on entering the page..
    // Is needed because we don't know the resolution of the user so it can't be done with css.
    changeBackgroundPosition();
});

It works fine, but it's also executed when resizing the browser in height. How can I check if the browser is horizontal resized so resizing the height can be ignored?

Of course it's possible to save the current window width and check if that's changed but I'm looking for nicer way (and to learn something I don't know yet;))!

As you can see, i've logged the 'e' of the resize function, but can't find anything usefull to me in it..

Hope to learn something of your suggestions. Thanks!


This is how I would "do something" if only the window width was changed. There is not much in the resize event object that let’s you detect this in a nicer way I’m afraid. Perhaps you can find something in experimenting with percentages in the background-position CSS property:

var $window = $(window),
    w = $window.width();

$window.resize(function(e) {
    if (w = $window.width() == w) {
        return;
    }
    console.log('width changed');
});


I hope you know that you can also set background-images centered via CSS.

background-position: center top; /* first value is horizontal alignment second is vertical*/
background-position: center center;
background-position: center bottom;

Or you can specify the background-position in percent too.

I don't know of any possibility to only address horizontal resizing except for the one you already mentioned (save the current window width and compare it). I don't see a problem with your suggested solution. Anybody correct me if there is a better way.


Wait, so body { background:#fff url(bg.jpg) no-repeat 50% 0; } doesn't cut it?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜