Javascript 如何使用JQuery根据屏幕大小实时更新CSS?

Javascript 如何使用JQuery根据屏幕大小实时更新CSS?,javascript,jquery,html,css,responsive,Javascript,Jquery,Html,Css,Responsive,我从以下回复中提取了一段JS: JS工作得很好,但只有当页面第一次加载时,如果屏幕大小因任何原因发生变化,则呈现的页面会出错,直到刷新为止 我目前有: $(document).ready(function() { var contentPlacement = $('#topMenu').position().top + $('#topMenu').height(); $('body').css('margin-top',contentPlacement); $('#navWindo

我从以下回复中提取了一段JS:

JS工作得很好,但只有当页面第一次加载时,如果屏幕大小因任何原因发生变化,则呈现的页面会出错,直到刷新为止

我目前有:

$(document).ready(function() {
  var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
  $('body').css('margin-top',contentPlacement);
  $('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
});
有没有办法让输出的CSS在屏幕大小更新时动态更改?这也将有助于开发网站

这将用于在固定菜单下显示我页面上的内容

更新


该站点的示例位于此处:

除了
ready
回调函数之外,您还可以使用它。您只需在resize回调上执行相同的代码。每次窗口大小更改时都会调用Resize

为了减少代码冗余,我引入了一种新方法
adjustContent

$(document).ready(adjustContent);

$(window).resize(adjustContent);

function adjustContent() {
    var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
    $('body').css('margin-top',contentPlacement);
    $('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
}

我知道您正在询问如何使用jQuery来更改CSS,但您真正应该做的是对CSS使用媒体查询,以便它是声明性的,而不是脚本/事件启动的

例:()


你们听说过媒体查询吗?你们能分享你们的网站吗?您不需要JS或jQuery来实现这一点。CSS
vw
vh
测量通常可以解决全屏问题是的,媒体查询是我使用的,但是当我需要频繁地更改它们时,以及在每次添加/更改某些内容时,使用它们都很烦人。至少有了这个,浏览器可以计算出完美值需要是多少。@GrafiCodeStudio视图宽度和视图高度可以由浏览器元设置,通常不可靠。shortround:
$(document).ready(function(){$(window).resize();})
$(文档).ready(函数(){adjustContent();})=
$(调整内容)ready
方法中使用任何类型的选择器都不推荐使用code>。@Shikkediel这是在哪里记录的?在中,我看不到这一点。它解释了第五个alinea的起始位置——“jQuery提供了几种附加函数的方法……”谢谢。调整了答案。
/* Set the background color of body to tan */
body {
  background-color: tan;
}

/* On screens that are 992px or less, set the background color to blue */
@media screen and (max-width: 992px) {
  body {
    background-color: blue;
  }
}

/* On screens that are 600px or less, set the background color to olive */
@media screen and (max-width: 600px) {
  body {
    background-color: olive;
  }
}