Изменение цвета при прокрутке не работает - PullRequest
1 голос
/ 20 апреля 2020

Я создал скрипт прокрутки, который позволяет мне менять цвет заголовка при прокрутке. Теперь я хочу использовать этот же скрипт для других элементов. Но я, кажется, застрял. Когда я копирую тот же скрипт, второй скрипт работает, но первый больше не будет работать.

Вы найдете мои html, css, javascript ниже. Надеюсь, кто-нибудь может помочь :) Спасибо

window.onscroll = () => {
  const div = document.querySelector('#navbar');
  if(this.scrollY <= 10) div.className = ''; else div.className = 'scroll';
};

window.onscroll = () => {
  const div = document.querySelector('#navbar2');
  if(this.scrollY <= 10) div.className = ''; else div.className = 'scroll';
};
html {
  position: relative;
  top: 0;
  left: 0;
  max-width: 100vw;
  min-height: 200vh;
  margin: 0px;
  padding: 0px;
  border: 0px;
}
body {
  padding: 1.7vmin;
  font-size: 16px;
  font-family: sans, sans-serif;
  color: #333;
}

a {
  color: inherit;
  font-style: italic;
}

#navbar {
  position: fixed;
  top: 0;
  left: 0;
  height: 3em;
  width: 100%;
  background-color: #EEE;
  box-sizing: border-box;
  padding: 12px 18px;
  box-shadow: 0px 4px 7px #777;
  transition: background-color 0.4s ease-out;
}
#navbar2{
  height:30px;
  background-color:red;
  position:fixed;
}

#navbar2.scroll{
  height:30px;
  background-color:blue;
}

#navbar span {
  font-weight: 600;
  letter-spacing: .085em;
}

#navbar button {
  position: absolute;
  top: 0;
  transform: translateY(50%);
  right: 0;
  min-height: 1.5em;
  min-width: 80px;
  background-color: #eee;
  color: #222;
  border: 0px;
  border-radius: 2px;
  margin-right: 18px;
  text-transform: uppercase;
}

#navbar.scroll {
  background-color: #A1572F;
  color: #eef;
}

body > header {
  margin-top: 4.7em;
}
<div id="navbar">
      <span>Hello, It's me</span>
      <button>Pickles!</button>
    </div>

    <header>
      <h1>Ode to a Large Tuna in the Market</h1>
      <h2>By Pablo Neruda</h2>
    </header>
<div id="navbar2">NAVBAR2</div>
    <article>
<p>Here,<br />among the market vegetables,<br />this torpedo<br />from the ocean<br />depths,<br />a missile<br />that swam,<br />now<br />lying in front of me<br />dead.</p>
<p>Surrounded<br />by the earth's green froth<br />—these lettuces,<br />bunches of carrots—<br />only you<br />lived through<br />the sea's truth, survived<br />the unknown, the<br />unfathomable<br />darkness, the depths<br />of the sea,<br />the great<br />abyss,<br /><em>le grand abîme</em>,<br />only you:<br />varnished<br />black-pitched<br />witness<br />to that deepest night.</p>
<p>Only you:<br />dark bullet<br />barreled   
<br />from the depths,<br />carrying<br />only<br />your<br />one wound,<br />but resurgent,<br />always renewed,<br />locked into the current,<br />fins fletched<br />like wings<br />in the torrent,<br />in the coursing<br />of<br />the<br />underwater<br />dark,<br />like a grieving arrow,<br />sea-javelin, a nerveless<br />oiled harpoon.</p>
<p>Dead<br />in front of me,<br />catafalqued king<br />of my own ocean;<br />once<br />sappy as a sprung fir<br />in the green turmoil,<br />once seed<br />to sea-quake,<br />tidal wave, now<br />simply<br />dead remains;<br />in the whole market<br />yours<br />was the only shape left<br />with purpose or direction<br />in this<br />jumbled ruin<br />of nature;<br />you are<br />a solitary man of war<br />among these frail vegetables,<br />your flanks and prow<br />black<br />and slippery<br />as if you were still<br />a well-oiled ship of the wind,<br />the only<br />true<br />machine<br />of the sea: unflawed,<br />undefiled,<br />navigating now<br />the waters of death.</p>
    </article>
    <footer>Extracted from <a href="https://www.poetryfoundation.org/poetrymagazine/poems/detail/49322">Poetry Foundation</a></footer>

1 Ответ

1 голос
/ 20 апреля 2020

window.onscroll = ... - это присвоение, поэтому, когда вы копируете ту же инструкцию, вы фактически переназначаете прослушиватель window.onscroll, поэтому запускается только самая последняя. Вместо этого вам нужно назначить его один раз и выполнить все дубликаты внутри:

window.onscroll = () => {
  changeColor(document.querySelector('#navbar'), this.scrollY);
  changeColor(document.querySelector('#navbar2'), this.scrollY);
};

function changeColor(div, scrollY) {
  if (scrollY <= 10) {
    div.className = ''; 
  } else {
    div.className = 'scroll';
  }
}
html {
  position: relative;
  top: 0;
  left: 0;
  max-width: 100vw;
  min-height: 200vh;
  margin: 0px;
  padding: 0px;
  border: 0px;
}
body {
  padding: 1.7vmin;
  font-size: 16px;
  font-family: sans, sans-serif;
  color: #333;
}

a {
  color: inherit;
  font-style: italic;
}

#navbar {
  position: fixed;
  top: 0;
  left: 0;
  height: 3em;
  width: 100%;
  background-color: #EEE;
  box-sizing: border-box;
  padding: 12px 18px;
  box-shadow: 0px 4px 7px #777;
  transition: background-color 0.4s ease-out;
}
#navbar2{
  height:30px;
  background-color:red;
  position:fixed;
}

#navbar2.scroll{
  height:30px;
  background-color:blue;
}

#navbar span {
  font-weight: 600;
  letter-spacing: .085em;
}

#navbar button {
  position: absolute;
  top: 0;
  transform: translateY(50%);
  right: 0;
  min-height: 1.5em;
  min-width: 80px;
  background-color: #eee;
  color: #222;
  border: 0px;
  border-radius: 2px;
  margin-right: 18px;
  text-transform: uppercase;
}

#navbar.scroll {
  background-color: #A1572F;
  color: #eef;
}

body > header {
  margin-top: 4.7em;
}
<div id="navbar">
      <span>Hello, It's me</span>
      <button>Pickles!</button>
    </div>

    <header>
      <h1>Ode to a Large Tuna in the Market</h1>
      <h2>By Pablo Neruda</h2>
    </header>
<div id="navbar2">NAVBAR2</div>
    <article>
<p>Here,<br />among the market vegetables,<br />this torpedo<br />from the ocean<br />depths,<br />a missile<br />that swam,<br />now<br />lying in front of me<br />dead.</p>
<p>Surrounded<br />by the earth's green froth<br />—these lettuces,<br />bunches of carrots—<br />only you<br />lived through<br />the sea's truth, survived<br />the unknown, the<br />unfathomable<br />darkness, the depths<br />of the sea,<br />the great<br />abyss,<br /><em>le grand abîme</em>,<br />only you:<br />varnished<br />black-pitched<br />witness<br />to that deepest night.</p>
<p>Only you:<br />dark bullet<br />barreled   
<br />from the depths,<br />carrying<br />only<br />your<br />one wound,<br />but resurgent,<br />always renewed,<br />locked into the current,<br />fins fletched<br />like wings<br />in the torrent,<br />in the coursing<br />of<br />the<br />underwater<br />dark,<br />like a grieving arrow,<br />sea-javelin, a nerveless<br />oiled harpoon.</p>
<p>Dead<br />in front of me,<br />catafalqued king<br />of my own ocean;<br />once<br />sappy as a sprung fir<br />in the green turmoil,<br />once seed<br />to sea-quake,<br />tidal wave, now<br />simply<br />dead remains;<br />in the whole market<br />yours<br />was the only shape left<br />with purpose or direction<br />in this<br />jumbled ruin<br />of nature;<br />you are<br />a solitary man of war<br />among these frail vegetables,<br />your flanks and prow<br />black<br />and slippery<br />as if you were still<br />a well-oiled ship of the wind,<br />the only<br />true<br />machine<br />of the sea: unflawed,<br />undefiled,<br />navigating now<br />the waters of death.</p>
    </article>
    <footer>Extracted from <a href="https://www.poetryfoundation.org/poetrymagazine/poems/detail/49322">Poetry Foundation</a></footer>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...