изменение размера и центрирование div в фиксированном положении с помощью jquery

#jquery #css #centering

#jquery #css #центрирование

Вопрос:

У меня есть div в фиксированном положении с фиксированной высотой / шириной.

Div позиционируется с помощью

положение: исправлено;

слева = 50%; margin-left = -(width/2) сверху = 50%; margin-top: = -(width /2)

Div имеет черный фон.

Что я хочу сделать, так это при нажатии кнопки вычислить размер нового содержимого (скрытого элемента dom)

Уберите содержимое div, анимируйте его изменение размера до нового размера содержимого (оставаясь по центру).

Добавьте новое содержимое.

Какой самый простой способ сделать это с помощью jQuery?

Комментарии:

1. я дал еще одно решение… попробуйте, чтобы это сработало.

Ответ №1:

вы также можете сделать это

 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
            });
        }
    }
}
  

Ответ №2:

Попробуйте это: 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>