如何在窗口调整大小时更改高度 div?
我的网站上有一个 div 应该是窗口的高度。 这就是我得到的:
$(document).ready(function() {
var bodyheight = $(document).height();
$("#sidebar").height(bodyheight);
});
但是,调整窗口大小时它不会自动更改?有谁知道如何解决这个问题?
谢谢
I have a div on my website that should be the height of the window.
This is what i got:
$(document).ready(function() {
var bodyheight = $(document).height();
$("#sidebar").height(bodyheight);
});
However, it does not automatically change when the window is resized? Does any body know how to fix this?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您还需要在
resize
事件中执行此操作,请尝试以下操作:You also need to do that in
resize
event, try this:只是为了显示对已接受答案的评论中建议的 DRY-up:
当然这有点愚蠢,因为它可以用 CSS 更简单地完成。但如果涉及到计算,那就另当别论了。例如,这个示例使 div 填充窗口底部,减去一点软糖因子。
Just to show the DRY-up suggested in the comment on the accepted answer:
And of course this is kind of silly since it is something that could be done with CSS more simply. But if there were a calculation involved that would be a different story. Eg this example which makes a div fill the bottom of the window, minus a little fudgefactor.
对此进行一些澄清,为了使窗口在每次回调后正确调整大小,您必须澄清要检索的高度。
否则,根据我的经验,无论您如何调整窗口大小,高度都会不断增加。这将采用当前窗口的高度。
Some clarification on this, in order for the window to resize correct after each callback you must clarify which height to retrieve.
Otherwise, from my experience, the height will keep increasing now matter how you resize the window. This will take the height of the current window.
除了其他人所说的之外,请确保将事件处理程序代码提取到单独的函数中,并从
ready
和resize
事件处理程序调用它。这样,如果您添加更多代码或需要将其绑定到其他事件,您将只有一个地方可以更改代码逻辑。In addition to what others have said make sure you extract the event handler code into a separate function and call it from
ready
andresize
event handlers. That way if you add some more code or need to bind it to other events you will have only one place where to change code logic.使用
resize
事件。这应该有效:
Use the
resize
event.This should work: