试图使代码更有效但它不起作用?

时间:2018-03-02 20:18:24

标签: javascript function

我对JavaScript不太满意,但我正在努力学习。我有所有这些功能分开工作,但它是丑陋和重复的。我试着清理它,在我的大脑中看起来应该可以工作,但事实并非如此。它也看起来不像我见过的其他代码,所以我猜我做错了。我做了什么?

原来一团糟:

function resizeHeaderOnScroll() {
  const distanceY = window.pageYOffset || 
  document.documentElement.scrollTop,
  shrinkOn = 200,
  headerEl = document.getElementById('header');

  if (distanceY > shrinkOn) {
    headerEl.classList.add('smaller');
  } else {
    headerEl.classList.remove('smaller');
  }
}
window.addEventListener('scroll', resizeHeaderOnScroll);


function resizeMarginOnScroll() {
  const distanceY = window.pageYOffset || 
  document.documentElement.scrollTop,
  shrinkOn = 200,
  aboutEl = document.getElementById('about');

  if (distanceY > shrinkOn) {
    aboutEl.classList.add('smaller-about');
  } else {
    aboutEl.classList.remove('smaller-about');
  }
}
window.addEventListener('scroll', resizeMarginOnScroll);


function toggleNavOnScroll() {
  const distanceY = window.pageYOffset || 
  document.documentElement.scrollTop,
  shrinkOn = 200,
  navEl = document.getElementById('nav');

  if (distanceY > shrinkOn) {
    navEl.classList.add('toggle-nav');
  } else {
    navEl.classList.remove('toggle-nav');
  }
}
window.addEventListener('scroll', toggleNavOnScroll);


function toggleLandingContentOnScroll() {
  const distanceY = window.pageYOffset || 
  document.documentElement.scrollTop,
  shrinkOn = 200;

  if (distanceY > shrinkOn) {
    document.getElementById('landing-full').style.display= 'none';
  } else {
    document.getElementById('landing-full').style.display= 'block';
  }
}
window.addEventListener('scroll', toggleLandingContentOnScroll);

尝试清理它:

function resizeHeaderOnScroll() {
  const distanceY = window.pageYOffset || 
  document.documentElement.scrollTop,
  shrinkOn = 200,
  headerEl = document.getElementById('header'),
  aboutEl = document.getElementById('about'),
  navEl = document.getElementById('nav');

  if (distanceY > shrinkOn) {
    headerEl.classList.add('smaller');
    aboutEl.classList.add('smaller-about');
    navEl.classList.add('toggle-nav');
    document.getElementById('landing-full').style.display= 'none';
  } else {
    headerEl.classList.remove('smaller');
    aboutEl.classList.remove('smaller-about');
    navEl.classList.remove('toggle-nav');
    document.getElementById('landing-full').style.display= 'block';
  }
}
window.addEventListener('scroll', resizeHeaderOnScroll);

0 个答案:

没有答案