Почему мой цвет шрифта в панели навигации не изменился, когда я переключился на sticky?

#javascript #html #css

#javascript #HTML #css — код

Вопрос:

Я все еще новичок в css и попытался создать липкую навигационную панель с фоном белого цвета и черным шрифтом. Я изо всех сил пытаюсь найти решение и не могу понять, что не так.

Вот как выглядит моя начальная панель навигации initial navbar

А вот прокручиваемая панель навигации Прокручиваемая панель навигации Изображение нечеткое, но шрифт по-прежнему белый с небольшим черным контуром, хотя я изменил цвет шрифта на черный

Вот мой HTML-код:

 <header id='navbar'>
  <a href="#" class="brand">LOGO</a>
  <div class="menu">
    <div class="btn">
      <i class="fas fa-times close-btn"></i>
    </div>
    <a href="#">Jadi Partner</a>
    <a href="#">Lapangan Favorit</a>
    <a href="#">Pesanan Saya</a>
    <div class="dropdown">
      <button class="dropbtn">
        <i class="fas fa-bars" id="menu-dropdown"></i><i class="fas fa-user-circle"></i>
      </button>
      <div class="dropdown-content">
        <a href="#">Log In</a>
        <a href="#">Sign Up</a>
      </div>
    </div>
  </div>
  <div class="btn">
    <i class="fas fa-bars menu-btn"></i>
  </div>

</header>


<script type="text/javascript">
  window.addEventListener('scroll', function () {
    // var header = document.querySelector('header');
    var header = document.querySelector('header');
    header.classList.toggle('sticky', window.scrollY > 0);
  })
</script>

<script type="text/javascript">
  //Javacript of responsive navigation menu
  const menuBtn = document.querySelector(".menu-btn");
  const navigation = document.querySelector(".navigation");

  menuBtn.addEventListener("click", () => {
    menuBtn.classList.toggle("active");
    navigation.classList.toggle("active");
  });

</script>
 

и это часть CSS:

 * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "Poppins", sans-serif;
}


header{
    z-index: 999;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 100px;
  transition: 0.6s;
}
header.sticky {
    background: #ffffff;
  padding: 20px 100px;
}


header .brand{
    color: #fff;
    font-size: 30px;
    font-weight: 700;
    text-transform: uppercase;
    text-decoration: none;
    letter-spacing: 2px;
  }

  header .menu{
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  header .menu a{
    color: rgb(255, 255, 255);
    font-size: 16px;
    font-weight: 500;
    text-decoration: none;
    margin: 0 30px;
    padding: 0 10px;
    border-radius: 20px;
    transition: 0.3s;
    transition-property: color, background;
  }

  header.sticky .menu a{
    color: black !important;
    z-index: 9999999;
  }
  
  header .menu a:hover{
    color: #000;
    background: #fff;
  }

  header .btn{
    color: #fff;
    font-size: 25px;
    cursor: pointer;
    display: none;
  }


.dropdown {
    float: right;
    position: relative;
    /* overflow: hidden; */
    margin-left: 10px;
}

.dropdown .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    font-family: inherit;
    margin-left: 20px;
    color: black;
    background-color: #fff;
    border-radius: 30px;
    padding: 0 3px;
}

.dropdown-content {
    display: none;
    position: absolute;
    top: calc(100%);
    right: 0;
    background-color: #ffffff;
    max-width: 160px;
    /* box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); */
    z-index: 9999;
    border-radius: 10px;
}

.dropdown-content a {
    /* float: none; */
    color: black !important;
    margin: 5px 0 !important;
    padding: 6px 10px;
    min-width: 120px;
    text-decoration: none;
    display: inline-block;
    font-size: .8em !important;
    /* text-align: left; */
    /* overflow: hidden; */
}

.dropdown-content a:hover {
    background-color: rgb(212, 212, 212);
}

.dropdown:hover .dropdown-content {
    display: block;
}




.navigation-items {
    display: flex;
    justify-content: center;
    align-items: center;
}



header .navigation .navigation-items #profile-dropdown {
    color: black;
    background-color: #fff;
    border-radius: 30px;
    padding: 0 3px;
}

.dropbtn i {
    margin: 0 3px;
}

#menu-dropdown {
    font-size: .7em;
}

header ul li a:before {
    content: '';
    position: absolute;
    background: rgb(255, 255, 255);
    border-color: #000000;
    width: 0;
    height: 3px;
    bottom: 0;
    left: 0;
    transition: 0.3s ease;
}

header ul li a:hover:before {
    width: 100%;
}
 

Эта часть отредактирована
Я обнаружил, что только с панелью навигации он работает отлично, но проблема возникает, когда я добавляю фоновое изображение под панелью навигации. Вот мой фоновый код под панелью навигации:

 <section class="home">
    <div class="images-home">
        <img src="{% static 'main/images/basketball.jfif' %}" alt="" class="image-slide">
        <img src="{% static 'main/images/prapoth-panchuea-OMWubltUEfE-unsplash.jpg' %}" alt="" class="image-slide">
        <img src="{% static 'main/images/muktasim-azlan-rjWfNR_AC5g-unsplash.jpg' %}" alt="" class="image-slide">
    </div>

    <div class="content">
        <h1>Train. Grow. Repeat.<br></h1>
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Maiores magnam quia vitae, animi unde consequuntur
            nihil doloribus quidem culpa, voluptatem, harum consequatur laboriosam delectus officia!</p>
        <a href="#">
            <span></span>
            <span></span>
            <span></span>
            <span></span> Booking sekarang</a>
    </div>

    <div class="slider-navigation">
        <div onclick="slider_nav(1)" class="nav-btn" id="radio1"></div>
        <div onclick="slider_nav(2)" class="nav-btn" id="radio2"></div>
        <div onclick="slider_nav(3)" class="nav-btn" id="radio3"></div>
    </div>

</section>
 

а вот CSS для фона:

 section {
    padding: 100px 200px;
}

.home {
    position: relative;
    width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    flex-direction: column;
    /* background: #267be9; */
    background: #ED1E1E;
}

.home:before {
    z-index: 777;
    content: '';
    position: absolute;
    /* background: rgba(62, 129, 245, 0.3); */
    background: rgba(212, 11, 11, 0.3);
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
}

.home .content {
    z-index: 888;
    /* color: #fff; */
    color: #fff;
    width: 60%;
    margin: 50px 70px;
    position: absolute;
    left: 0%;
}

.home .content h1 {
    font-size: 3.5em;
    font-weight: 700;
    /* text-transform: uppercase; */
    letter-spacing: 5px;
    line-height: 75px;
    margin-bottom: 40px;
}

.home .content p {
    margin-bottom: 65px;
    max-width: 50%;
    /* font-size: 1.2vw; */
}

.home .content a {
    /* background: #fff; */
    width: 30%;
    background: #ED1E1E;
    padding: 15px 35px;
    /* color: #1680AC; */
    /* color: #ED1E1E; */
    color: #ffffff;
    /* font-size: 1.1em; */
    font-size: 1.4vw;
    font-weight: 500;
    text-decoration: none;
    text-transform: uppercase;
    position: relative;
    /* display: flex; */
}

.home .content a:hover {
    color: var(--main-color);
    background-color: #fff;
}

.home .content a span {
    display: block;
    position: absolute;
    background: var(--main-color);
}

.home .content a span:nth-child(1) {
    left: 0;
    bottom: 0;
    width: 2px;
    height: 100%;
    transform: scaleY(0);
    transform-origin: top;
    transition: transform 0.5s;
}

.home .content a:hover span:nth-child(1) {
    transform: scaleY(1);
    transform-origin: bottom;
    transition: transform 0.5s;
}

.home .content a span:nth-child(2) {
    left: 0;
    bottom: 0;
    width: 100%;
    height: 2px;
    transform: scaleX(0);
    transform-origin: right;
    transition: transform 0.5s;
}

.home .content a:hover span:nth-child(2) {
    transform: scaleX(1);
    transform-origin: left;
    transition: transform 0.5s;
}

.home .content a span:nth-child(3) {
    right: 0;
    bottom: 0;
    width: 2px;
    height: 100%;
    transform: scaleY(0);
    transform-origin: top;
    transition: transform 0.5s;
    transition-delay: 0.5s;
}

.home .content a:hover span:nth-child(3) {
    transform: scaleY(1);
    transform-origin: bottom;
    transition: transform 0.5s;
    transition-delay: 0.5s;
}

.home .content a span:nth-child(4) {
    left: 0;
    top: 0;
    width: 100%;
    height: 2px;
    transform: scaleX(0);
    transform-origin: right;
    transition: transform 0.5s;
    transition-delay: 0.5s;
}

.home .content a:hover span:nth-child(4) {
    transform: scaleX(1);
    transform-origin: left;
    transition: transform 0.5s;
    transition-delay: 0.5s;
}

.home img {
    z-index: 000;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.home .media-icons {
    z-index: 888;
    position: absolute;
    right: 30px;
    display: flex;
    flex-direction: column;
    transition: 0.5s ease;
}

.home .media-icons a {
    color: #fff;
    font-size: 1.6em;
    transition: 0.3s ease;
}

.home .media-icons a:not(:last-child) {
    margin-bottom: 20px;
}

.home .media-icons a:hover {
    transform: scale(1.3);
}

.slider-navigation {
    z-index: 888;
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    /* transform: translateY(80px); */
    /* margin-bottom: 12px; */
    bottom: 5%;
    left: 50%;
    transform: translateX(-50%);
}

.slider-navigation .nav-btn {
    width: 12px;
    height: 12px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    box-shadow: 0 0 2px rgba(255, 255, 255, 0.5);
    transition: 0.3s ease;
}

.slider-navigation .nav-btn:not(:last-child) {
    margin-right: 20px;
}

.slider-navigation .nav-btn:hover {
    transform: scale(1.2);
}

.slider-navigation .nav-btn.active {
    background: var(--main-color);
}

@media (max-width: 1040px) {
    section {
        padding: 100px 20px;
    }
    .home .content {
        margin: 0 20px;
    }
    .home .media-icons {
        right: 15px;
    }
    .home .content h1 {
        font-size: 4vw;
        line-height: 60px;
    }
    .home .content p {
        margin-bottom: 65px;
        max-width: 40%;
        font-size: 13px;
    }
}

@media (max-width: 560px) {
    .home .content {
        margin: 0 20px;
    }
    .home .content h1 {
        /* font-size: 2em; */
        line-height: 60px;
    }
    .home .content p {
        margin-bottom: 65px;
        max-width: 40%;
        font-size: 10px;
    }
    .home .content a {
        max-width: 10px;
        padding: 10px 25px;
    }
}
 

Я кое-что прочитал о !важно, но это не помогло. Спасибо всем, кто готов помочь такому любителю, как я 🙂

Комментарии:

1. Я добавил ваш код в codepen, и он работал нормально, пожалуйста, проверьте codepen.io/shahilparichay/pen/KKXMqLy

2. О, я думаю, что все испортил раздел фона под панелью навигации, поскольку использование только панели навигации работает отлично.

3. да, он работал нормально, только ему не хватало высоты для прокрутки

Ответ №1:

Вам нужно добавить background-color color свойство and в селектор заголовка, а не header .sticky .

Поскольку вы динамически добавляете класс sticky, поэтому при первом рендеринге цвета фактически не видны.

Обновить

Проверил ваш codepen, и вам не хватает свойства, когда класс .sticky применяется через JS

 header.sticky .dropdown .dropbtn {
    background-color: #000;
}

header.sticky .brand{
    color: #000;
  }
 

Комментарии:

1. Проверьте мое прикрепленное изображение, моя начальная панель навигации в порядке, но при прокрутке вниз цвет шрифта не изменился. Я меняю цвет шрифта при прокрутке внутри header.sticky a .

2. Обновил мой ответ с помощью CSS

3. Да, он отлично работает, когда используется только navbar. Вот почему я обновил свой вопрос и свой код, проблема возникает, когда я добавляю фон под панелью навигации. Проверьте мое прикрепленное изображение, чтобы получить четкое представление о моей проблеме.

4. Можете ли вы предоставить codepen для второго сценария?

5. после того, как я скопировал весь свой код в codepen, он, похоже, работает нормально. Оказывается, у меня проблема в моем {% block head %} разделе, и я уже исправил ее. Спасибо за вашу помощь!