[英]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? 在開發站點時這也將有所幫助。
這將用於在固定菜單下的頁面上顯示內容。
UPDATE
該站點的示例位於: http : //wp19.knowgreaterpartnership.com/
除了ready
回調函數之外,您還可以使用jquery.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使用Media Queries,以便它是聲明性的,而不是腳本/事件啟動的。
例如:( 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.