即使浏览器窗口改变大小,jQuery也会找出元素宽度

时间:2011-09-13 12:35:19

标签: jquery

我有以下jQuery代码,找出容器的宽度,然后告诉子元素是一定的大小(减去侧边栏的大小),以便它将填满屏幕。

除了用户更改浏览器窗口不更新外,它工作正常除外!所以我需要jQuery代码才能实时工作。有人可以帮忙吗?感谢

$(document).ready(function () {

    // find out the width of the page
    var pageWidth = $('div.MainContentHolder').width();
    // minus the sidebar and margin width
    var middleWidth = pageWidth - '220';
    // apply the new width to the middle column
    $('div.MiddleColumn').css('width', middleWidth);

});

2 个答案:

答案 0 :(得分:3)

你只需要将它绑定到$(window).resize();

$(document).ready(function () {

    $(window).resize(function() {
        // find out the width of the page
        var pageWidth = $('div.MainContentHolder').width();
        // minus the sidebar and margin width
        var middleWidth = pageWidth - '220';
        // apply the new width to the middle column
        $('div.MiddleColumn').css('width', middleWidth);
    }).resize();

});

答案 1 :(得分:1)

将代码移至单独的函数,并在document readywindow resize事件中同时运行:

function resizeElements() {
    // find out the width of the page
    var pageWidth = $('div.MainContentHolder').width();
    // minus the sidebar and margin width
    var middleWidth = pageWidth - '220';
    // apply the new width to the middle column
    $('div.MiddleColumn').css('width', middleWidth);
}

$(document).ready(function () {
    resizeElements();
    $(window).resize(resizeElements);
}