首页 > 解决方案 > 如何基于innerWidth JavaScript native添加或删除函数

问题描述

目前我正在尝试在屏幕宽度大于或小于时添加/删除功能,但下面的代码不起作用,有什么建议吗?

window.addEventListener('resize', () => {
    if(window.innerHeight > 768){
       window.addEventListener('scroll', scrolling);
    }else{
       window.removeEventListener('scroll', scrolling);
       sectionFixedNavLeftSide.firstElementChild.classList.remove('fixed-sidebar-home');
       sectionFixedNavLeftSide.firstElementChild.classList.remove('fixed-bottom-sidebar')
    }
});

回调滚动:

const scrolling = () => {
      sectionFixedNavLeftSide.getBoundingClientRect().top <= (screen.width / 
      50 * 2.7) ? 
      sectionFixedNavLeftSide.firstElementChild.classList.add('fixed- 
      sidebar-home') : 
      sectionFixedNavLeftSide.firstElementChild.classList.remove('fixed- 
      sidebar-home');
      
      sectionFixedNavRightSide.getBoundingClientRect().bottom - screen.width 
      / 2.85 <= 0 ? 
      sectionFixedNavLeftSide.firstElementChild.classList.add('fixed-bottom- 
      sidebar') : 
      sectionFixedNavLeftSide.firstElementChild.classList.remove('fixed- 
      bottom-sidebar');
}

标签: javascript

解决方案


推荐阅读