如何根据屏幕尺寸实时更新 CSS,使用 JQuery?

How to live update CSS based on screen size, using JQuery?

我从以下回复中提取了一段 JS: 如何让内容显示在固定的 DIV 元素下方?

JS 工作得很好,但只有在页面首次加载时,如果屏幕尺寸因任何原因发生变化,呈现的页面就会出错,直到刷新。

我目前有这个:

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

有没有办法让输出的 CSS 在屏幕尺寸更新时动态变化?这对开发网站也很有帮助。

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

更新

站点示例位于此处:http://wp19.knowgreaterpartnership.com/

除了 ready 回调函数之外,您还可以使用 jquery.resize。您只需在调整大小回调上执行相同的代码。每次 window 大小更改时都会调用 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 使用媒体查询,这样它是声明性的而不是script/event 发起。

例如:(https://www.w3schools.com/Css/css3_mediaqueries_ex.asp)

/* 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;
  }
}