Изменить цвет липкой панели навигации с помощью javascript

Я начал с белого фона навигационной панели и по мере прокрутки меняю его на фиолетовый. Здесь я хочу, чтобы элементы списка были белого цвета, но я не могу этого сделать. Вот полные исходные коды в HTML, CSS и JS.

// jshint esversion: 6
window.onscroll = function() { myFunction(); };

let navbar = document.getElementsByClassName("navigation")[0];
let sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
       navbar.classList.add("sticky");
  } else {
       navbar.classList.remove("sticky");
  }
}
/* ------------------------------------- */
/* BASIC RESET */
/* ------------------------------------- */
* {
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

html { font-size: 62.5%; }

body {
     box-sizing: inherit;
     color: #777;
     background-color: #fff;
     font-family: 'Roboto', sans-serif;
     font-size: 1.8rem;
     font-weight: 400;
     line-height: 1.5;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* ------------------------------------- */
/* THE REUSABLE CONTENT */
/* ------------------------------------- */

/* HTML contents */

h1, h2.header-heading, h2 {
     margin: 0;
     text-transform: uppercase;
}

h1 {
     font-size: 4.5rem;
     color: #fff;
     letter-spacing: .4rem;
     word-spacing: .5rem;
     font-weight: 300;
}

h2 {
     font-size: 3.5rem;
}

/* Links */

a {
     text-decoration: none;
     display: inline-block;
}

/* Buttons */

.btn {
     border: 1px solid #fff;
     border-radius: .3rem;
     font-size: 1.6rem;
     padding: 1.2rem 3.5rem;
     text-transform: uppercase;
     color: #fff;
     background-color: transparent;
     font-weight: bold;
     letter-spacing: .3rem;
     transition: all .2s;
}

.btn:hover {
     background-color: #fff;
     color: #000;
}

/* Utility classes */

.u-margin-top-small {
     margin-top: 2.5rem;
}

.u-text-align-center {
     text-align: center;
}

.u-inline-block {
     display: inline-block;
}

/* ------------------------------------- */
/* THE HEADER SECTION */
/* ------------------------------------- */

header {
     background-color: #353353;
     height: 98vh;
}

.hero-text-box {
     position: absolute;
     top: 40%;
     left: 50%;
     transform: translate(-50%, -50%);
}

h2.header-heading {
     font-size: 3.5rem;
     margin-top: 2rem;
     color: #FFE800;
     font-weight: 400;
}

/* ------------------------------------- */
/* THE NAVBAR */
/* ------------------------------------- */

.navigation {
     position: relative;
     padding: 1rem;
     border-bottom: .5px solid #777;
}

.logo-box {
     float: left;
}

.logo {
     color: #353353;
     text-transform: uppercase;
     font-weight: 700;
     font-size: 4rem;
     letter-spacing: .4rem;
     margin-left: 5rem;
}

nav {
     padding: 1rem;
}

.navbar {
     float: right;
     list-style: none;
     margin-right: 10rem;
     margin-top: 1.5rem;
}

.navbar li {
     display: inline-block;
}

.navbar li a {
     margin: 0 1rem;
     padding: .2rem .6rem;
     color: black;
     text-transform: uppercase;
     border-bottom: 2px solid transparent;
     transition: all .3s;
}

.navbar li a:hover {
     border-bottom: 2px solid red;
}

/* The sticky navbar */

.sticky {
     position: fixed;
     background-color: #353353;
     top: 0;
     width: 100%;
}
<!DOCTYPE html>
<html lang = "en">
<head>
     <!-- Required meta tags -->
     <meta charset = "UTF-8">
     <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
     <meta http-equiv = "X-UA-Compatible" content = "ie=edge">

     <!-- Rubik fonts link -->
     <link rel = "preconnect" href = "https://fonts.gstatic.com">
     <link href = "https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;700&display=swap" rel = "stylesheet">

     <!-- CSS links -->
     <link rel = "stylesheet" href = "css/normalize.css">
     <link rel = "stylesheet" href = "css/styles.css">

     <title>Arun Bohra - Design Business Solutions</title>
</head>
<body>

     <header>
          <div class = "hero-text-box u-text-align-center u-inline-block">
               <h1>Hello my name is Arun</h1>
               <h2 class = "header-heading u-margin-top-small">I'm a front-end developer</h2>
               <a href = "#" class = "btn u-margin-top-small u-inline-block">Who am I</a>
          </div>
     </header>

     <div class = "navigation">
          <nav class = "clearfix">
               <div class = "logo-box">
                    <a href = "#" class = "logo">
                         Arun
                    </a>
               </div>

               <ul class = "navbar">
                    <li><a href = "#" class = "navbar-lists">Home</a></li>
                    <li><a href = "#" class = "navbar-lists">About me</a></li>
                    <li><a href = "#" class = "navbar-lists">Skills</a></li>
                    <li><a href = "#" class = "navbar-lists">Projects</a></li>
                    <li><a href = "#" class = "navbar-lists">Contact</a></li>
               </ul>
          </nav>
     </div>

     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>

     <script src = "js/index.js" charset = "utf-8"></script>
</body>


</html>

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

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
47
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Вы можете просто выбрать элемент с помощью этого селектора: .navigation.sticky > nav > ul > li > a и изменить цвет на белый. Он выберет элемент <a> в списке навигационной панели, если блок .navigation также имеет класс .sticky.

// jshint esversion: 6
window.onscroll = function() { myFunction(); };

let navbar = document.getElementsByClassName("navigation")[0];
let sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
       navbar.classList.add("sticky");
  } else {
       navbar.classList.remove("sticky");
  }
}
/* ------------------------------------- */
/* BASIC RESET */
/* ------------------------------------- */
* {
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

html { font-size: 62.5%; }

body {
     box-sizing: inherit;
     color: #777;
     background-color: #fff;
     font-family: 'Roboto', sans-serif;
     font-size: 1.8rem;
     font-weight: 400;
     line-height: 1.5;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* ------------------------------------- */
/* THE REUSABLE CONTENT */
/* ------------------------------------- */

/* HTML contents */

h1, h2.header-heading, h2 {
     margin: 0;
     text-transform: uppercase;
}

h1 {
     font-size: 4.5rem;
     color: #fff;
     letter-spacing: .4rem;
     word-spacing: .5rem;
     font-weight: 300;
}

h2 {
     font-size: 3.5rem;
}

/* Links */

a {
     text-decoration: none;
     display: inline-block;
}

/* Buttons */

.btn {
     border: 1px solid #fff;
     border-radius: .3rem;
     font-size: 1.6rem;
     padding: 1.2rem 3.5rem;
     text-transform: uppercase;
     color: #fff;
     background-color: transparent;
     font-weight: bold;
     letter-spacing: .3rem;
     transition: all .2s;
}

.btn:hover {
     background-color: #fff;
     color: #000;
}

/* Utility classes */

.u-margin-top-small {
     margin-top: 2.5rem;
}

.u-text-align-center {
     text-align: center;
}

.u-inline-block {
     display: inline-block;
}

/* ------------------------------------- */
/* THE HEADER SECTION */
/* ------------------------------------- */

header {
     background-color: #353353;
     height: 98vh;
}

.hero-text-box {
     position: absolute;
     top: 40%;
     left: 50%;
     transform: translate(-50%, -50%);
}

h2.header-heading {
     font-size: 3.5rem;
     margin-top: 2rem;
     color: #FFE800;
     font-weight: 400;
}

/* ------------------------------------- */
/* THE NAVBAR */
/* ------------------------------------- */

.navigation {
     position: relative;
     padding: 1rem;
     border-bottom: .5px solid #777;
}

.logo-box {
     float: left;
}

.logo {
     color: #353353;
     text-transform: uppercase;
     font-weight: 700;
     font-size: 4rem;
     letter-spacing: .4rem;
     margin-left: 5rem;
}

nav {
     padding: 1rem;
}

.navbar {
     float: right;
     list-style: none;
     margin-right: 10rem;
     margin-top: 1.5rem;
}

.navbar li {
     display: inline-block;
}

.navbar li a {
     margin: 0 1rem;
     padding: .2rem .6rem;
     color: black;
     text-transform: uppercase;
     border-bottom: 2px solid transparent;
     transition: all .3s;
}

.navbar li a:hover {
     border-bottom: 2px solid red;
}

/* The sticky navbar */

.sticky {
     position: fixed;
     background-color: #353353;
     top: 0;
     width: 100%;
}

.navigation.sticky > nav > ul > li > a {
  color: white!important;
}
<!DOCTYPE html>
<html lang = "en">
<head>
     <!-- Required meta tags -->
     <meta charset = "UTF-8">
     <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
     <meta http-equiv = "X-UA-Compatible" content = "ie=edge">

     <!-- Rubik fonts link -->
     <link rel = "preconnect" href = "https://fonts.gstatic.com">
     <link href = "https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;700&display=swap" rel = "stylesheet">

     <!-- CSS links -->
     <link rel = "stylesheet" href = "css/normalize.css">
     <link rel = "stylesheet" href = "css/styles.css">

     <title>Arun Bohra - Design Business Solutions</title>
</head>
<body>

     <header>
          <div class = "hero-text-box u-text-align-center u-inline-block">
               <h1>Hello my name is Arun</h1>
               <h2 class = "header-heading u-margin-top-small">I'm a front-end developer</h2>
               <a href = "#" class = "btn u-margin-top-small u-inline-block">Who am I</a>
          </div>
     </header>

     <div class = "navigation">
          <nav class = "clearfix">
               <div class = "logo-box">
                    <a href = "#" class = "logo">
                         Arun
                    </a>
               </div>

               <ul class = "navbar">
                    <li><a href = "#" class = "navbar-lists">Home</a></li>
                    <li><a href = "#" class = "navbar-lists">About me</a></li>
                    <li><a href = "#" class = "navbar-lists">Skills</a></li>
                    <li><a href = "#" class = "navbar-lists">Projects</a></li>
                    <li><a href = "#" class = "navbar-lists">Contact</a></li>
               </ul>
          </nav>
     </div>

     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>

     <script src = "js/index.js" charset = "utf-8"></script>
</body>


</html>

Могу я сделать то же самое с логотипом на панели навигации.

Arun Bohra 30.03.2021 09:57

Для логотипа вы можете использовать этот селектор: .navigation.sticky > nav > .logo-box > .logo

Rifat Bin Reza 30.03.2021 10:01
Ответ принят как подходящий

Просто выберите липкий класс, чтобы изменить цвет ссылки следующим образом: .navigation.sticky .navbar li a{color: #fff}

// jshint esversion: 6
window.onscroll = function() { myFunction(); };

let navbar = document.getElementsByClassName("navigation")[0];
let sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
       navbar.classList.add("sticky");
  } else {
       navbar.classList.remove("sticky");
  }
}
/* ------------------------------------- */
/* BASIC RESET */
/* ------------------------------------- */
* {
     margin: 0;
     padding: 0;
     box-sizing: border-box;
}

html { font-size: 62.5%; }

body {
     box-sizing: inherit;
     color: #777;
     background-color: #fff;
     font-family: 'Roboto', sans-serif;
     font-size: 1.8rem;
     font-weight: 400;
     line-height: 1.5;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* ------------------------------------- */
/* THE REUSABLE CONTENT */
/* ------------------------------------- */

/* HTML contents */

h1, h2.header-heading, h2 {
     margin: 0;
     text-transform: uppercase;
}

h1 {
     font-size: 4.5rem;
     color: #fff;
     letter-spacing: .4rem;
     word-spacing: .5rem;
     font-weight: 300;
}

h2 {
     font-size: 3.5rem;
}

/* Links */

a {
     text-decoration: none;
     display: inline-block;
}

/* Buttons */

.btn {
     border: 1px solid #fff;
     border-radius: .3rem;
     font-size: 1.6rem;
     padding: 1.2rem 3.5rem;
     text-transform: uppercase;
     color: #fff;
     background-color: transparent;
     font-weight: bold;
     letter-spacing: .3rem;
     transition: all .2s;
}

.btn:hover {
     background-color: #fff;
     color: #000;
}

/* Utility classes */

.u-margin-top-small {
     margin-top: 2.5rem;
}

.u-text-align-center {
     text-align: center;
}

.u-inline-block {
     display: inline-block;
}

/* ------------------------------------- */
/* THE HEADER SECTION */
/* ------------------------------------- */

header {
     background-color: #353353;
     height: 98vh;
}

.hero-text-box {
     position: absolute;
     top: 40%;
     left: 50%;
     transform: translate(-50%, -50%);
}

h2.header-heading {
     font-size: 3.5rem;
     margin-top: 2rem;
     color: #FFE800;
     font-weight: 400;
}

/* ------------------------------------- */
/* THE NAVBAR */
/* ------------------------------------- */

.navigation {
     position: relative;
     padding: 1rem;
     border-bottom: .5px solid #777;
}

.logo-box {
     float: left;
}

.logo {
     color: #353353;
     text-transform: uppercase;
     font-weight: 700;
     font-size: 4rem;
     letter-spacing: .4rem;
     margin-left: 5rem;
}

nav {
     padding: 1rem;
}

.navbar {
     float: right;
     list-style: none;
     margin-right: 10rem;
     margin-top: 1.5rem;
}

.navbar li {
     display: inline-block;
}

.navbar li a {
     margin: 0 1rem;
     padding: .2rem .6rem;
     color: black;
     text-transform: uppercase;
     border-bottom: 2px solid transparent;
     transition: all .3s;
}

.navbar li a:hover {
     border-bottom: 2px solid red;
}

/* The sticky navbar */

.sticky {
     position: fixed;
     background-color: #353353;
     top: 0;
     width: 100%;
}

.navigation.sticky .navbar li a {
  color: #fff;
}
<!DOCTYPE html>
<html lang = "en">
<head>
     <!-- Required meta tags -->
     <meta charset = "UTF-8">
     <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
     <meta http-equiv = "X-UA-Compatible" content = "ie=edge">

     <!-- Rubik fonts link -->
     <link rel = "preconnect" href = "https://fonts.gstatic.com">
     <link href = "https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;700&display=swap" rel = "stylesheet">

     <!-- CSS links -->
     <link rel = "stylesheet" href = "css/normalize.css">
     <link rel = "stylesheet" href = "css/styles.css">

     <title>Arun Bohra - Design Business Solutions</title>
</head>
<body>

     <header>
          <div class = "hero-text-box u-text-align-center u-inline-block">
               <h1>Hello my name is Arun</h1>
               <h2 class = "header-heading u-margin-top-small">I'm a front-end developer</h2>
               <a href = "#" class = "btn u-margin-top-small u-inline-block">Who am I</a>
          </div>
     </header>

     <div class = "navigation">
          <nav class = "clearfix">
               <div class = "logo-box">
                    <a href = "#" class = "logo">
                         Arun
                    </a>
               </div>

               <ul class = "navbar">
                    <li><a href = "#" class = "navbar-lists">Home</a></li>
                    <li><a href = "#" class = "navbar-lists">About me</a></li>
                    <li><a href = "#" class = "navbar-lists">Skills</a></li>
                    <li><a href = "#" class = "navbar-lists">Projects</a></li>
                    <li><a href = "#" class = "navbar-lists">Contact</a></li>
               </ul>
          </nav>
     </div>

     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>
     <h1>This is the primary heading.</h1>

     <script src = "js/index.js" charset = "utf-8"></script>
</body>


</html>

Вы можете просто добавить CSS, чтобы он работал:

.sticky .navbar-lists {
    color: white;
}

Css автоматически обновит ваш новый стиль, если он правильно соответствует вашим тегам html. Я бы также посоветовал вам поставить transition, когда вы меняете свой UX / UI, пользователи могут быть потеряны, если это произойдет слишком быстро.

Да, я сделаю это. Я только начинаю этим заниматься. Все цвета на пробу.

Arun Bohra 30.03.2021 10:02

Измените стили для navbar li a с помощью приведенного ниже примера. И тоже добавьте новые стили.

.navbar:not(.light-navbar) li a {
    color: #000;
}

.light-navbar li a {
    color: #fff;
}

.navbar li a {
     margin: 0 1rem;
     padding: .2rem .6rem;
     text-transform: uppercase;
     border-bottom: 2px solid transparent;
     transition: all .3s;
}

Добавьте изменения в JavaScript

// jshint esversion: 6
window.onscroll = myFunction;

let navbar = document.getElementsByClassName("navigation")[0];
let targetNav = document.querySelector('.navigation .navbar');
let sticky = navbar.offsetTop;

function myFunction () {
  if (window.pageYOffset >= sticky) {
       navbar.classList.add("sticky");
       targetNav.classList.add('light-navbar');
  } else {
       navbar.classList.remove("sticky");
       targetNav.classList.remove('light-navbar');
  }
}

Другие вопросы по теме