Выделить/добавить класс в активный div

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

$(document).ready(function() {
  $("nav ul li a").on('click', function() {
    var Target = $(this).attr("anchor");
    var Location = $("#" + Target).position();

    $(".content").removeClass("active");
    $("#" + Target).addClass("active");

    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(".content").on("click", function() {
    $(".content").removeClass("active");
    $(this).addClass("active");

    var Location = $(this).position();
    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(window).click(function() {
    $(".content").removeClass("active");
  });

  $('.content,nav ul li a').click(function(event) {
    event.stopPropagation();
  });
});
body {
  background: rgb(255, 255, 255);
  color: rgb(0, 0, 0);
  margin: 0;
  padding-top: 3em;
  font-size: 1rem;
}

.content {
  background: black;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 1em;
  margin: 0 auto;
  margin-top: 3em;
  margin-bottom: 3em;
  width: 80%;
}

.content p {
  max-width: 900px;
}

@media (min-width: 700px) {
  .header {
    background: rgba(0, 0, 0, 0.75);
    width: 80%;
    text-align: center;
    padding: 0.25em 5%;
    position: fixed;
    top: 0;
    left: 5%;
    border-bottom-left-radius: 1em;
    border-bottom-right-radius: 1em;
    display: block;
    z-index: 1;
    -webkit-user-select: none;
    user-select: none;
    border: solid transparent 1px;
  }
  .header:hover {
    background: rgba(0, 0, 0, 1);
  }
  nav ul {
    list-style-type: none;
    display: inline-block;
  }
  nav ul li {
    display: inline-block;
  }
  nav ul li a {
    color: white;
    text-decoration: none;
    padding: 1em;
    font-weight: bold;
    border-radius: 0.25em;
    cursor: pointer;
  }
  nav ul li a:hover {
    color: black;
    background: white;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 3em;
    margin-bottom: 3em;
    width: 80%;
  }
}

@media (max-width:700px) {
  .header {
    display: none;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 1em;
    margin-bottom: 3em;
    width: 80%;
  }
}

.active {
  background: #ddd;
  color: black;
}
<!DOCTYPE html>
  <html>

  <head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <div class = "header">
      <nav>
        <ul>
          <li><a anchor = "home">Home</a></li>
          <li><a anchor = "services">Services</a></li>
          <li><a anchor = "safety">Safety</a></li>
          <li><a anchor = "about">About Us</a></li>
          <li><a anchor = "contact">Contact</a></li>
        </ul>
      </nav>
    </div>
    <div id = "home" class = "content">
      <h1>My Random Website</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "services" class = "content">
      <h1>Services</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "safety" class = "content">
      <h1>Safety</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "about" class = "content">
      <h1>About</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "contact" class = "content">
      <h1>Contact</h1>
      Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into the
      Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of theology,
      biology, science, medicine, and law.
    </div>
  </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
84
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Используя ниже jQuery, вы можете активировать класс при прокрутке, когда достигнете вершины

$(document).ready(function() {
    $(window).scroll(function(){  
     var topMenuHeight = $('.header').outerHeight() + 30;
     var fromTop = $(this).scrollTop() + topMenuHeight; 
     $('.content').each(function() {
       if ($(this).offset().top < fromTop){
         var id = $(this).attr('id');
         $('.content').removeClass('active');
         $('#'+ id).addClass('active');
       }
       else{
         var id = $(this).attr('id');
         $('#'+ id).removeClass('active');
       }  
     });
   });
  $("nav ul li a").on('click', function() {
    var Target = $(this).attr("anchor");
    var Location = $("#" + Target).position();

    $(".content").removeClass("active");
    $("#" + Target).addClass("active");

    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(".content").on("click", function() {
    $(".content").removeClass("active");
    $(this).addClass("active");

    var Location = $(this).position();
    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(window).click(function() {
    $(".content").removeClass("active");
  });

  $('.content,nav ul li a').click(function(event) {
    event.stopPropagation();
  });
});
body {
  background: rgb(255, 255, 255);
  color: rgb(0, 0, 0);
  margin: 0;
  padding-top: 3em;
  font-size: 1rem;
}

.content {
  background: black;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 1em;
  margin: 0 auto;
  margin-top: 3em;
  margin-bottom: 3em;
  width: 80%;
}

.content p {
  max-width: 900px;
}

@media (min-width: 700px) {
  .header {
    background: rgba(0, 0, 0, 0.75);
    width: 80%;
    text-align: center;
    padding: 0.25em 5%;
    position: fixed;
    top: 0;
    left: 5%;
    border-bottom-left-radius: 1em;
    border-bottom-right-radius: 1em;
    display: block;
    z-index: 1;
    -webkit-user-select: none;
    user-select: none;
    border: solid transparent 1px;
  }
  .header:hover {
    background: rgba(0, 0, 0, 1);
  }
  nav ul {
    list-style-type: none;
    display: inline-block;
  }
  nav ul li {
    display: inline-block;
  }
  nav ul li a {
    color: white;
    text-decoration: none;
    padding: 1em;
    font-weight: bold;
    border-radius: 0.25em;
    cursor: pointer;
  }
  nav ul li a:hover {
    color: black;
    background: white;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 3em;
    margin-bottom: 3em;
    width: 80%;
  }
}

@media (max-width:700px) {
  .header {
    display: none;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 1em;
    margin-bottom: 3em;
    width: 80%;
  }
}

.active {
  background: #ddd;
  color: black;
}
<!DOCTYPE html>
  <html>

  <head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <div class = "header">
      <nav>
        <ul>
          <li><a anchor = "home">Home</a></li>
          <li><a anchor = "services">Services</a></li>
          <li><a anchor = "safety">Safety</a></li>
          <li><a anchor = "about">About Us</a></li>
          <li><a anchor = "contact">Contact</a></li>
        </ul>
      </nav>
    </div>
    <div id = "home" class = "content">
      <h1>My Random Website</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "services" class = "content">
      <h1>Services</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "safety" class = "content">
      <h1>Safety</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "about" class = "content">
      <h1>About</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "contact" class = "content">
      <h1>Contact</h1>
      Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into the
      Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of theology,
      biology, science, medicine, and law.
    </div>
  </body>

  </html>

Вау, это именно то, что я искал. Спасибо, однако, есть ли способ сделать активным только один div в любое время.

Jacob 25.02.2019 05:31

@Jacob Проверьте обновленный фрагмент только для одного активного класса

Hiren Vaghasiya 25.02.2019 05:54

О, это было простое решение, я должен был это увидеть. Спасибо!

Jacob 25.02.2019 14:59

Попробуй это.

$(document).ready(function() {
  $("nav ul li a").on('click', function() {
    var Target = $(this).attr("anchor");
    var Location = $("#" + Target).position();

    $(".content").removeClass("active");
    $("#" + Target).addClass("active");

    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(".content").on("click", function() {
    $(".content").removeClass("active");
    $(this).addClass("active");

    var Location = $(this).position();
    $("html, body").animate({
      scrollTop: Location.top - 30
    }, 350);
  });
  $(window).click(function() {
    $(".content").removeClass("active");
  });
  var start = $('.content').first();
  var lastScrollTop = 0;
  $(document).scroll(function(event){
     var st = $(this).scrollTop();
     if (st > lastScrollTop){
        if ($(this).scrollTop()>= start.position().top){
                updateClass();
          start = start.next();        
        }
     } else {
        if ($(this).scrollTop()<= start.position().top){
                updateClass();
          start = start.prev();        
        }
     }
     lastScrollTop = st;
  }); 
    function updateClass(){
      $(".content").removeClass("active");
        start.addClass("active");
  } 

  $('.content,nav ul li a').click(function(event) {
    event.stopPropagation();
  });
});
body {
  background: rgb(255, 255, 255);
  color: rgb(0, 0, 0);
  margin: 0;
  padding-top: 3em;
  font-size: 1rem;
}

.content {
  background: black;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 1em;
  margin: 0 auto;
  margin-top: 3em;
  margin-bottom: 3em;
  width: 80%;
}

.content p {
  max-width: 900px;
}

@media (min-width: 700px) {
  .header {
    background: rgba(0, 0, 0, 0.75);
    width: 80%;
    text-align: center;
    padding: 0.25em 5%;
    position: fixed;
    top: 0;
    left: 5%;
    border-bottom-left-radius: 1em;
    border-bottom-right-radius: 1em;
    display: block;
    z-index: 1;
    -webkit-user-select: none;
    user-select: none;
    border: solid transparent 1px;
  }
  .header:hover {
    background: rgba(0, 0, 0, 1);
  }
  nav ul {
    list-style-type: none;
    display: inline-block;
  }
  nav ul li {
    display: inline-block;
  }
  nav ul li a {
    color: white;
    text-decoration: none;
    padding: 1em;
    font-weight: bold;
    border-radius: 0.25em;
    cursor: pointer;
  }
  nav ul li a:hover {
    color: black;
    background: white;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 3em;
    margin-bottom: 3em;
    width: 80%;
  }
}

@media (max-width:700px) {
  .header {
    display: none;
  }
  .content {
    background: black;
    color: white;
    border: none;
    border-radius: 10px;
    padding: 1em;
    margin: 0 auto;
    margin-top: 1em;
    margin-bottom: 3em;
    width: 80%;
  }
}

.active {
  background: #ddd;
  color: black;
}
<!DOCTYPE html>
  <html>

  <head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <div class = "header">
      <nav>
        <ul>
          <li><a anchor = "home">Home</a></li>
          <li><a anchor = "services">Services</a></li>
          <li><a anchor = "safety">Safety</a></li>
          <li><a anchor = "about">About Us</a></li>
          <li><a anchor = "contact">Contact</a></li>
        </ul>
      </nav>
    </div>
    <div id = "home" class = "content">
      <h1>My Random Website</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "services" class = "content">
      <h1>Services</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "safety" class = "content">
      <h1>Safety</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "about" class = "content">
      <h1>About</h1>
      <p>Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into
        the Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of
        theology, biology, science, medicine, and law.</p>
    </div>
    <div id = "contact" class = "content">
      <h1>Contact</h1>
      Latin was originally spoken in the area around Rome, known as Latium.[4] Through the power of the Roman Republic, it became the dominant language, initially in Italy and subsequently throughout the western Roman Empire. Vulgar Latin developed into the
      Romance languages, such as Italian, Portuguese, Spanish, French, and Romanian. Latin, Greek, and French have contributed many words to the English language. In particular, Latin (and Ancient Greek) roots are used in English descriptions of theology,
      biology, science, medicine, and law.
    </div>
  </body>

  </html>

Ниже мой код

var start = $('.content').first();
  var lastScrollTop = 0;
  $(document).scroll(function(event){
     var st = $(this).scrollTop();
     if (st > lastScrollTop){
        if ($(this).scrollTop()>= start.position().top){
                updateClass();
          start = start.next();        
        }
     } else {
        if ($(this).scrollTop()<= start.position().top){
                updateClass();
          start = start.prev();        
        }
     }
     lastScrollTop = st;
  }); 
    function updateClass(){
      $(".content").removeClass("active");
        start.addClass("active");
  } 

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