當用戶向下滾動視口超過 50 像素時,我的 if 陳述句會調整標題中的一堆元素。一旦用戶滾動回小于 50px,它會使用 else 陳述句重新調整回正常。目前,除了我在 else 陳述句中的 img 高度和寬度之外,一切正常。出于某種原因,代碼在 if/else 陳述句中移動到 30px 后不會反彈到 60px 的高度。請讓我知道您認為 else 陳述句有什么問題。我認為這與專門捕捉影像有關。
HTML
<img class="header-logo-img header-logo-img-illustration" id="header-logo-img-illustration" src="../imgs/NoahPointingIllustration.png" alt="logo illustration" height="60" width="60">
CSS
// When the user scrolls down 50px from the top of the page, resize the header
$(document).ready(function () {
window.onscroll = function() {
dynamicHeaderOnScroll()
};
function dynamicHeaderOnScroll() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.getElementById("header-wrapper").style.maxWidth = "100%";
document.getElementById("header").style.paddingTop = "10px";
document.getElementById("header").style.paddingBottom = "0.4em";
// Reposition "close hamburger menu" icon
document.getElementById("closebtn").style.margin = "-43px 0 0 0";
document.getElementById("header-logo-img-illustration").style.height = "30px";
document.getElementById("header-logo-img-illustration").style.width = "30px";
} else {
document.getElementById("header-wrapper").style.maxWidth = "900px";
document.getElementById("header").style.paddingTop = "55px";
document.getElementById("header").style.paddingBottom = "0.25em";
document.getElementById("header-homepage").style.paddingBottom = "1em";
// Reposition "close hamburger menu" icon
document.getElementById("closebtn").style.margin = "0";
document.getElementById("header-logo-img-illustration").style.height = "60px"; // ISSUE HERE
document.getElementById("header-logo-img-illustration").style.width = "60px"; // ISSUE HERE
};
};
頁面加載時標題中的大影像:
您可以在此處看到由于以下錯誤導致代碼崩潰:
Uncaught TypeError: Cannot read properties of null (reading 'style')
at dynamicHeaderOnScroll (main.js:144)
at window.onscroll (main.js:130)
...發生在這一行:
document.getElementById("header-homepage").style.paddingBottom = "1em";
因此,它抱怨無法style從 value讀取屬性,尤其是null。從那以后,document.getElementById("header-homepage")必須回傳,null以便您基本上做到了null.style.paddingBottom,因此出現了錯誤。為什么會這樣?因為header-homepage您的頁面上沒有帶有 ID 的元素。
旁注:根據類在 CSS 中使用這些樣式會更有意義。
例如,您可以is-scrolled在<body>標簽上使用一個類- 然后您的所有 JS 代碼需要做的是document.body.classList.add('is-scrolled')(remove當然還有 )。
然后,您將在樣式表中定義規則,例如:
body.is-scrolled #closebtn {
margin: -43px 0 0 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/346975.html
標籤:javascript html 查询
