0

I am using the following Jquery script to center the container div in the middle of the window. The problem comes when the user has a resolution that is smaller than the container, as when the site loads the top of the div is chopped off. How can I set the function only to trigger if the browser size or resolution is bigger than the container div ?.

<script>
    $(window).load(function(){
        var positionContent = function () {
            var width = $(window).width(); // the window width
            var height = $(window).height(); // the window height
            var containerwidth = $('.container').outerWidth(); // the container div width
            var containerheight = $('.container').outerHeight(); // the container div height
            $('.container').css({position:'absolute',
                left: ($(window).width() - $('.container').outerWidth())/2,
                top: ($(window).height() - $('.container').outerHeight())/2 }); 
        };
        //Call this when the window first loads
        $(document).ready(positionContent);
        //Call this whenever the window resizes.
        $(window).bind('resize', positionContent);
    });
</script>
4

1 回答 1

1

只需将窗口尺寸与容器尺寸进行比较,如果容器比窗口​​高/宽,则将顶部/左侧位置设置为 0:

$('.container').css({
    position: 'absolute',
    left: width > containerwidth ? (width - containerwidth) / 2 : 0,
    top: height > containerheight ? (height - containerheight) / 2 : 0
});

顺便说一句,您已经定义了widthheightcontainerwidthcontainerheight,所以我不确定您为什么不在代码中重用它们。

于 2013-07-25T10:09:02.253 回答