[英]How can I change the color of the <nav> when I scroll on mobile?
我已經在台式機上做到了,但是當我嘗試使用移動設備編寫代碼時,由於某種原因它崩潰了
window.onscroll = () => {
const nav = document.querySelector('#navbar');
var viewportWidth = $(window).width();
if (viewportWidth > 1020) {
if(this.scrollY <= 500) nav.className = ''; else nav.className = 'scroll';}
};
響應式設計通常很難使用JS進行仿真,因此對JS所做的工作不做多余的事情:
window.onscroll = () => {
const nav = document.querySelector('#navbar');
nav.className = (this.scrollY <= 500) ? '' : 'scroll';
};
並使用CSS媒體查詢來僅在移動設備上更改顏色:
#navbar.scroll {
/* when scrolling on desktop */
background-color: green;
}
@media screen and (max-width: 1019px) {
#navbar.scroll {
/* when scrolling on tablets or mobile */
background-color: red;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.