确保我的滑动面板在窗口调整大小时保持居中?

时间:2011-08-04 15:44:58

标签: javascript jquery

我创建了一个滑动面板,应该出现在任何大小的窗口的中心,我的问题是我在我的css计算周围添加了window.resize,这似乎不起作用,当页面调整大小然后窗口崩溃?

我的代码如下:

$(document).ready(function() {
        var $userPanel = $('div.panel');

        // hide div.panel then show it and slide into view
        $userPanel.hide().delay(2000);
        $userPanel.show('slide', { direction: 'up' });

        // work out the window width / 2 to get the center and the same for div.panel
        var windowWidth = $(window).width() / 2;
        var panelWidth = $userPanel.width() / 2;
        // subtract the div.panel width from the window width / 2
        var positionCentered = windowWidth - panelWidth;

        // add css to the left property of position absolute
        $(window).resize($userPanel.css({ left: windowWidth - panelWidth })); // ???????????????

        $('#closeMe').click(function(e) {
            e.preventDefault();
            $userPanel.hide('slide', { direction: 'up' });
        });
    });

任何人都可以就我出错的地方向我提出一些建议吗?

此致 凯尔

1 个答案:

答案 0 :(得分:2)

如果面板的宽​​度没有改变,你不需要监听resize事件 - 你可以直接做CSS

div.panel {
    width: 500px; // example
    position:absolute;
    left: 50%;
    margin-left: -250px; // negative half of width
}

更新:如果你想要一个居中的可变宽度面板,你可以(而且应该)仍然使用CSS:

div.panel {
    width: auto;
    position:absolute;
    left:  200px;
    right: 200px;
}

然后应该拉伸面板以实现左/右约束。

至于代码(我之前看起来并不太难),这就是为什么我认为它失败了 - 只知道,我不是一个jQuery人,所以我可能错了。

  1. 当页面加载时,您只计算一次位置,因此resize处理程序如果有效,只需反复设置相同的left值。
  2. resize处理程序应该是一个函数。现在它是一个函数调用,它返回一个jQuery包装的元素。因此,当调整大小时,它会尝试调用对象,就像它是一个函数一样。
  3. 你的选择器匹配类'panel'的所有div元素,所以即使你只有1个面板,你仍然会得到一个列表,而不仅仅是一个元素。我想你想要一个特定的元素(在这种情况下你应该使用id而不是类来识别它)。否则,您需要为列表中的每个元素设置位置。但从代码判断,看起来你正试图使用​​列表,就好像它是一个单独的元素,所以我猜你只有一个面板。
  4. 所以试试这个(但仍然首先尝试CSS方法):

    $(document).ready(function() {
        $(window).resize(function() { // everything must take place inside the event handler
            var panel = $('div#userpanel'); // get the panel by its id, not its class
    
            panel.hide().delay(2000);
            panel.show('slide', {direction: 'up'});
    
            var leftOffset = ($(this).width() - panel.width()) / 2;
            panel.css({
              left: String(leftOffset) + 'px'
            });
        });
    
        $('#closeMe').click(function(e) {
            e.preventDefault();
            $('div#userpanel').hide('slide', { direction: 'up' });
        });
    });
    
相关问题