我创建了一个滑动面板,它应该出现在任何大小的窗口的中心,但是我的问题是我在我的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' });
});
});
有人可以给我一些关于我哪里出错的建议吗?
问候 凯尔
最佳答案
如果面板的宽度没有改变,你不需要监听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;
}
然后面板应该拉伸(stretch)以满足左/右约束。
至于代码(我之前没有仔细看过),这就是我认为它失败的原因 - 只是知道,我不是 jQuery 人员,所以我可能是错的。
- 您只在页面加载时计算位置一次,因此如果有效,
resize
处理程序只需再次设置相同的left
值即可再次。 resize
处理程序应该是一个函数。现在它是一个函数call,它返回一个 jQuery 包装的元素。因此,当调整大小时,它会尝试调用该对象,就好像它是一个函数一样。- 您的选择器匹配“panel”类的所有 div 元素,因此即使您只有 1 个面板,您仍然会得到一个列表,而不仅仅是一个元素。我想你想要一个单一的、特定的元素(在这种情况下,你应该使用 id 而不是类来标识它)。否则,您需要设置列表中每个元素的位置。但从代码来看,您似乎正在尝试将列表视为单个元素,因此我猜您只有一个面板。
所以尝试这个(但仍然首先尝试 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' });
});
});
关于javascript - 确保我的滑动面板在窗口调整大小时保持居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944448/