【问题标题】:How can I change the color of the <nav> when I scroll on mobile?在移动设备上滚动时如何更改 <nav> 的颜色?
【发布时间】:2018-07-14 23:58:36
【问题描述】:

我已经在台式机上完成了,但是当我在移动设备上尝试代码时,由于某种原因它崩溃了

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

};

【问题讨论】:

  • 什么移动平台?您确定该平台支持粗箭头功能吗?
  • 我认为您可能需要重新考虑将更改应用于 nav 元素的方法。滚动时您正在不断地编辑className。

标签: javascript mobile scroll


【解决方案1】:

响应式设计往往很难用 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;
  }
}

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多