【问题标题】:Center a flexible div with jQuery使用 jQuery 将灵活的 div 居中
【发布时间】:2014-01-11 12:24:48
【问题描述】:

所以我有这个 div,它包含一个表单,其中验证消息淡入淡出,改变了 div 的宽度和高度。我有一些 jQuery 来使 div 居中,但我遇到的问题是当验证消息淡入并调整 div 的大小时 jQuery 没有响应。

我需要一些代码来监听 div 的宽度和高度?

我目前拥有的代码

resizeElement = '.blurHolder';

var holderHeight = jQuery(resizeElement).outerHeight();
var holderWidth = jQuery(resizeElement).outerWidth();

jQuery(resizeElement).css({
    'margin-top': - holderHeight / 2,
    'margin-left': - holderWidth / 2
});

有什么帮助吗?

【问题讨论】:

标签: javascript jquery css


【解决方案1】:

试试这个:

html

<div class="container">
 <div class="blurHolder"></div>
</div>

css

.container{
    background: orange;
    width: 400px;
    height: 400px;
    float: left;
    margin: 10px;
}

.container .blurHolder{
    width: 100px;
    height: 100px;
    background: #333;
}

js

$( document ).ready(function() {

    var containerHeight = $('.container').height();
    var containerWidth = $('.container').width();
    var offsetTop = (containerHeight - $('.container').find('.blurHolder').height())/2;
    var offsetLeft = (containerWidth - $('.container').find('.blurHolder').width())/2;

    $('.container').css({'padding-top': offsetTop, 'padding-left': offsetLeft, 'height': containerHeight - offsetTop, 'width': containerWidth - offsetLeft});

});

【讨论】:

    【解决方案2】:

    我刚刚搜索了library

    看起来您可以像编写代码一样简单地检测到onresizeonresize 事件:

    new ResizeSensor($('#someDiv'), yourCallbackFunction);
    

    顺便说一句。有一个原生的onresize事件,但它只被IE支持,你可以阅读here

    【讨论】:

      【解决方案3】:

      将位置代码更改为'margin-top' : (holderHeight/2) - (divHeight/2)

      并将其应用于剩余边距。还有设置的位置是什么,绝对的还是相对的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-13
        • 2018-10-10
        • 2015-06-17
        • 2012-12-03
        • 1970-01-01
        • 1970-01-01
        • 2015-11-14
        • 1970-01-01
        相关资源
        最近更新 更多