0

Имеется гамбургер меню белого цвета. Проблема в том, что в моем проекте в некоторых местах сайта его не видно из-за неконтрастного фона. Задача состоит в написании скрипта, который должен менять цвет в зависимости от цвета фона на контрастный этому цвету. В коде ниже, для примера, на черном фоне меню должно стать белым. Изначальный план был присвоить каждому блоку свой id и когда иконка меню попадает на новую секцию, она меняет свой цвет. Но в силу слабого знания js не получилось. Так же ссылка на codepen: https://codepen.io/RukUndead/pen/VwZzQRP

@import url(https://fonts.googleapis.com/css?family=Quicksand);
html,
body {
   height: 100%;
   background-color: red;
   font-family: 'Quicksand', sans-serif;
   color: white;
}


#menuToggle
{
  display: block;
  position: fixed;
  top: 50px;
  left: 50px;
  
  z-index: 1;
  
  -webkit-user-select: none;
  user-select: none;
}

#menuToggle input
{
  display: block;
  width: 40px;
  height: 32px;
  position: absolute;
  top: -7px;
  left: -5px;
  
  cursor: pointer;
  
  opacity: 0; /* hide this */
  z-index: 2; /* and place it over the hamburger */
  
  -webkit-touch-callout: none;
}

/*
 * Just a quick hamburger
 */
#menuToggle span
{
  display: block;
  width: 33px;
  height: 4px;
  margin-bottom: 5px;
  position: relative;
  
  background: #000;
  border-radius: 3px;
  
  z-index: 1;
  
  transform-origin: 4px 0px;
  
  transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
              background 0.5s cubic-bezier(0.77,0.2,0.05,1.0),
              opacity 0.55s ease;
}

#menuToggle span:first-child
{
  transform-origin: 0% 0%;
}

#menuToggle span:nth-last-child(2)
{
  transform-origin: 0% 100%;
}

/* 
 * Transform all the slices of hamburger
 * into a crossmark.
 */
#menuToggle input:checked ~ span
{
  opacity: 1;
  transform: rotate(45deg) translate(-2px, -1px);
  background: #232323;
}

/*
 * But let's hide the middle one.
 */
#menuToggle input:checked ~ span:nth-last-child(3)
{
  opacity: 0;
  transform: rotate(0deg) scale(0.2, 0.2);
}

/*
 * Ohyeah and the last one should go the other direction
 */
#menuToggle input:checked ~ span:nth-last-child(2)
{
  transform: rotate(-45deg) translate(0, -1px);
}

/*
 * Make this absolute positioned
 * at the top left of the screen
 */
#menu
{
  position: absolute;
  width: 300px;
  margin: -100px 0 0 -50px;
  padding: 50px;
  padding-top: 125px;
  
  background: #ededed;
  list-style-type: none;
  -webkit-font-smoothing: antialiased;
  /* to stop flickering of text in safari */
  
  transform-origin: 0% 0%;
  transform: translate(-100%, 0);
  
  transition: transform 0.5s cubic-bezier(0.77,0.2,0.05,1.0);
}

#menu li
{
  padding: 10px 0;
  font-size: 22px;
}

/*
 * And let's slide it in from the left
 */
#menuToggle input:checked ~ ul
{
  transform: none;
}
<nav role="navigation">
  <div id="menuToggle">

    <input type="checkbox" />

    <span></span>
    <span></span>
    <span></span>

    <ul id="menu">
      <a href="#"><li>Home</li></a>
      <a href="#"><li>About</li></a>
      <a href="#"><li>Info</li></a>
      <a href="#"><li>Contact</li></a>
      <a href="https://erikterwan.com/" target="_blank"><li>Show me more</li></a>
    </ul>
  </div>
</nav>


<div class="container" id=#slide-1>
   <div class="row">
      <div class="col-sm-10 col-sm-push-1 col-md-8 col-md-push-2">
         <h1>Full Screen Burger Menu</h1>
         <h3>Click the burger.</h3>
         <p>Lucas ipsum dolor sit amet darth lando qui-gonn mara droid jade qui-gonn skywalker wedge lars. Ben antilles chewbacca palpatine mothma fisto binks mara. Wicket greedo c-3p0 han lars mara darth. Darth binks wookiee mara luuke amidala. Lando kessel jango wicket. Moff jango dantooine luuke skywalker obi-wan. Darth mandalore binks leia solo moff yoda. Darth c-3p0 maul ben jar lando. Jabba ahsoka grievous mandalorians kenobi wookiee chewbacca. Binks calrissian tatooine baba jango k-3po darth calamari yavin.</p>
         <p>
            Wicket sidious organa skywalker mandalore mon qui-gonn fisto. Leia grievous biggs bespin calamari. Alderaan luuke darth hutt. Vader leia boba kashyyyk dagobah jade kashyyyk. Lars amidala gonk lobot organa. Twi'lek darth gamorrean obi-wan boba moff. Yavin c-3p0 darth darth luke chewbacca han. Skywalker dooku c-3po owen. Leia jade alderaan jar dooku utapau tusken raider dantooine jawa. Anakin leia kessel jango bespin lando organa tatooine tusken raider. Mara ackbar mara calamari hutt qui-gonn dantooine.
         </p>
         <p>
            Yoda sidious lando padmé chewbacca fett. Maul calrissian boba lobot jade darth obi-wan. Wookiee darth ahsoka dagobah darth sidious naboo lars. Dooku skywalker skywalker ben luke windu. Wicket darth coruscant darth coruscant organa palpatine yoda padmé. Darth leia organa gonk lando mon mara hutt. Wookiee darth padmé windu hutt. Darth cade maul padmé grievous greedo moff dooku solo. Coruscant twi'lek dooku moff skywalker.
         </p>
      </div>
   </div>
</div>

<div class="container" style="background-color:#000;width:100%;" id=#slide-2>
   <div class="row">
      <div class="col-sm-10 col-sm-push-1 col-md-8 col-md-push-2">
         <h1>Full Screen Burger Menu</h1>
         <h3>Click the burger.</h3>
         <p>Lucas ipsum dolor sit amet darth lando qui-gonn mara droid jade qui-gonn skywalker wedge lars. Ben antilles chewbacca palpatine mothma fisto binks mara. Wicket greedo c-3p0 han lars mara darth. Darth binks wookiee mara luuke amidala. Lando kessel jango wicket. Moff jango dantooine luuke skywalker obi-wan. Darth mandalore binks leia solo moff yoda. Darth c-3p0 maul ben jar lando. Jabba ahsoka grievous mandalorians kenobi wookiee chewbacca. Binks calrissian tatooine baba jango k-3po darth calamari yavin.</p>
         <p>
            Wicket sidious organa skywalker mandalore mon qui-gonn fisto. Leia grievous biggs bespin calamari. Alderaan luuke darth hutt. Vader leia boba kashyyyk dagobah jade kashyyyk. Lars amidala gonk lobot organa. Twi'lek darth gamorrean obi-wan boba moff. Yavin c-3p0 darth darth luke chewbacca han. Skywalker dooku c-3po owen. Leia jade alderaan jar dooku utapau tusken raider dantooine jawa. Anakin leia kessel jango bespin lando organa tatooine tusken raider. Mara ackbar mara calamari hutt qui-gonn dantooine.
         </p>
         <p>
            Yoda sidious lando padmé chewbacca fett. Maul calrissian boba lobot jade darth obi-wan. Wookiee darth ahsoka dagobah darth sidious naboo lars. Dooku skywalker skywalker ben luke windu. Wicket darth coruscant darth coruscant organa palpatine yoda padmé. Darth leia organa gonk lando mon mara hutt. Wookiee darth padmé windu hutt. Darth cade maul padmé grievous greedo moff dooku solo. Coruscant twi'lek dooku moff skywalker.
         </p>
      </div>
   </div>
</div>

3
  • 1
    Почему бы не сделать гамбургер белым, а при коллапсе менять его цвет на черный?
    – Mully
    2 сен 2019 в 8:17
  • Конечно можно это реализовать через js, но вам придется просчитывать положение гамбургера, относительно элементов и потом динамически менять цвет, да еще и если он только половиной зайдет на другой цвет, а другой ногой будет еще в красном, как тогда? Задайте ему фон, кргуом, залейте его цветом, чтобы он выделялся. Вычисления на подобии положения гамбургера относительно элементов, еще и одно временно, еще и проблемы с наложением цвета. Браузер такого точно не одобрит в плане производительности
    – Mully
    2 сен 2019 в 8:20

1 ответ 1

1

Ну такой вариант тоже возможен, но такое себе. Надо только дописать условия под разные девайсы

let span = document.querySelectorAll('#menuToggle span');
window.addEventListener('scroll', function ( event ) {
   let width = document.documentElement.clientWidth;
   console.log(width)
   console.log(pageYOffset)
   for ( let i = 0; i < span.length; i++ ) {
      if ( width >= 620 ) {
         if ( pageYOffset >= 420 ) {
            span[i].style.backgroundColor = '#fff';
         } else {
            span[i].style.backgroundColor = '#000';
         }
      }
   }
})

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.