使用jquery调整固定位置div的大小和居中

时间:2011-05-02 03:34:50

标签: jquery css centering

我有一个固定高度/宽度的固定位置div。

使用

定位div

职位:固定;

左= 50%; margin-left = - (width / 2) 最高= 50%; margin-top:= - (width / 2)

div有黑色背景。

我想要做的是,按下按钮时计算新内容的大小(隐藏的dom元素)

淡出div的内容,将其调整为新的内容大小(保持居中)。

淡化新内容。

使用jQuery执行此操作的最简单方法是什么?

2 个答案:

答案 0 :(得分:0)

你也可以这样做

this=$('#yourDiv');

    this.css("position","absolute");
        this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");

这是我的一个应用程序,尝试它应该集中在它

如果您需要任何自定义,请重构。

function centerPopup() {

    var windowWidth = document.body.clientWidth;
    var windowHeight = document.body.clientHeight;
    var popupHeight = $('#popupplaceholder').height();
    var popupWidth = $('#popupplaceholder').width();
        if (popupWidth > windowWidth) {
        popupWidth = (windowWidth) * (0.9);
    }
    if (popupHeight > windowHeight) {
        popupHeight = (windowHeight) * (0.9);
    }
    //centering
    var objControl = document.getElementById("yourDIV");
    if (objControl != null) {
        if (objControl.offsetParent != null) {
            var left = (objControl.offsetParent.clientWidth / 2) - (objControl.clientWidth / 2) + objControl.offsetParent.scrollLeft;
            var top = (objControl.offsetParent.clientHeight / 2) - (objControl.clientHeight / 2) + objControl.offsetParent.scrollTop;
            $('#yourDIV').css({
                "position": "absolute",
                "top": top,
                "left": left
            });
        }
    }
}

答案 1 :(得分:0)

试试这个:http://jsfiddle.net/EpzDM/

它有效,但我不怀疑JavaScript可以改进。

<强> JavaScript的:

var $box = $('#box');
var $boxInner = $box.find(' > div');

var fixIt = function() {
    var newWidth = 300;
    var newHeight = 150;

    $boxInner.fadeOut(function() {
        $box.animate({
            marginLeft: -newWidth/2,
            marginTop: -newHeight/2,
            width: newWidth,
            height: newHeight
        }, 500, function() {
            $boxInner.fadeIn();
        });
    });
};

$(window).resize(function() {
    $box.css({
        marginLeft: -$box.width()/2,
        marginTop: -$box.height()/2
    });
}).resize();

$('<button>Clicky!</button>').appendTo(document.body).click(fixIt).css({
    position: 'fixed',
    top: 0,
    left: 0
});

<强> CSS:

#box {
    width: 200px;
    height: 100px;
    background: #ccc;
    position: fixed;
    left: 50%;
    top: 50%
}

<强> HTML:

<div id="box">
    <div>
        <p>Contents of div</p>
        <p>Contents of div</p>
        <p>Contents of div</p>
    </div>
</div>
相关问题