简体   繁体   English

我该如何改变颜色 <nav> 当我在手机上滚动时?

[英]How can I change the color of the <nav> when I scroll on mobile?

I already did it on desktop, but when I try the code with mobile, it crashes for some reason 我已经在台式机上做到了,但是当我尝试使用移动设备编写代码时,由于某种原因它崩溃了

    window.onscroll = () => {
  const nav = document.querySelector('#navbar');
 var viewportWidth = $(window).width();        
if (viewportWidth > 1020) {
        if(this.scrollY <= 500) nav.className = ''; else nav.className = 'scroll';}

};

Responsive design tends to be really hard to emulate using JS, so don't do more than necessary with JS: 响应式设计通常很难使用JS进行仿真,因此对JS所做的工作不做多余的事情:

window.onscroll = () => {
  const nav = document.querySelector('#navbar');
  nav.className = (this.scrollY <= 500) ? '' : 'scroll';
};

And use CSS media queries to have the color only be changed on mobile: 并使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM