为了账号安全,请及时绑定邮箱和手机立即绑定

当相应部分在屏幕上时,将活动类添加到 li

当相应部分在屏幕上时,将活动类添加到 li

宝慕林4294392 2022-10-08 10:02:39
我只有一个页面。我的页面上至少有四个部分。active当滚动到相应部分的底部时,我必须将类添加到菜单上的 li 标记中。例如,如果屏幕上有关于我们的部分,则将活动类添加到 li 标签。如果画廊部分在屏幕上,则添加活动类并从前一个 li 中删除活动类。我必须更改颜色并将底部边框添加到活动菜单列表中。我不想使用任何插件。这是一个例子。它正在添加活动类并更改导航列表的颜色 https://blackrockdigital.github.io/startbootstrap-scrolling-nav/可以使用 jQuery 吗?$(function() {  $('.smothscrollclass a[href*="#"]:not([href="#"])').click(function() {    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {      var target = $(this.hash);      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');      if (target.length) {        $('html, body').animate({          scrollTop: target.offset().top - 100        }, 1000);        return false;      }    }  });});body {  margin: 0;  padding: 0;}.headerMenu {  position: fixed;  top: 0;  width: 100%;  background-color: #d9a6a6;}.anchorLinks ul {  list-style: none;}.anchorLinks ul li {  display: inline-block;  margin: 15px;}.anchorLinks ul li a {  color: #fff;  text-decoration: none;  font-size: 18px;}.anchorLinks ul li.active a {  color: #ffef00;  border-bottom: 1px solid #000;}.WrapperInner {  margin-top: 80px;  margin-bottom: 80px;}section {  height: 400px;  padding: 40px;}section p {  color: #fff;}.aboutus {  background-color: #ec7063;}.service {  background-color: #a569bd;}.gallery {  background-color: #5dade2;}.contactus {  background-color: #2ecc71;}<div class="Wrapper">  <div class="mainInner bg_white">    <div class="linkWrappers">      <header class="headerMenu">        <div class="anchorLinks smothscrollclass">          <ul>            <li><a href="">Home</a></li>            <li><a href="#aboutus">About</a></li>            <li><a href="#service">Service</a></li>            <li><a href="#gallery">Gallery</a></li>            <li><a href="#contactus">Contact</a></li>          </ul>        </div>      </header>    </div>
查看完整描述

3 回答

?
红颜莎娜

TA贡献1842条经验 获得超13个赞

嗨,跟进下面的代码片段,我在这里所做的是一个名为activateLink的函数,我为链接提供了 ID,然后单击链接我在 jquery 的帮助下向该特定 li 添加了一个活动类


$(function() {

  $('.smothscrollclass a[href*="#"]:not([href="#"])').click(function() {

    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {

      var target = $(this.hash);

      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

      if (target.length) {

        $('html, body').animate({

          scrollTop: target.offset().top - 100

        }, 1000);

        return false;

      }

    }

  });

});


function activateLink (link,section) {

if(section){

    $('html, body').animate({

        'scrollTop' : $("#"+section).position().top

    },function(){    

       $( ".active" ).removeClass( "active" )

       $("#"+link).addClass("active");

    });

}else{

 $( ".active" ).removeClass( "active" )

 $("#"+link).addClass("active")

 

}

 

}


function checkSectionExistance (sectionId,linkId) {

 var element = document.querySelector('#'+sectionId);

  var position = element.getBoundingClientRect();


// checking for partial visibility

  if(position.top < window.innerHeight && position.bottom >= 0) {

      $( ".active" ).removeClass( "active" )

 $("#"+linkId).addClass("active")

  }

}


window.addEventListener('scroll', function() {

  

  checkSectionExistance('aboutus','about-link')

  checkSectionExistance('service','service-link')

  checkSectionExistance('gallery','gallery-link')

  checkSectionExistance('contactus','contact-link')

  

     

  

  

});

body {

  margin: 0;

  padding: 0;

}


.headerMenu {

  position: fixed;

  top: 0;

  width: 100%;

  background-color: #d9a6a6;

}


.anchorLinks ul {

  list-style: none;

}


.anchorLinks ul li {

  display: inline-block;

  margin: 15px;

}


.anchorLinks ul li a {

  color: #fff;

  text-decoration: none;

  font-size: 18px;

}


.anchorLinks ul li.active a {

  color: #ffef00;

  border-bottom: 1px solid #000;

}


.WrapperInner {

  margin-top: 80px;

  margin-bottom: 80px;

}


section {

  height: 400px;

  padding: 40px;

}


section p {

  color: #fff;

}


.aboutus {

  background-color: #ec7063;

}


.service {

  background-color: #a569bd;

}


.gallery {

  background-color: #5dade2;

}


.contactus {

  background-color: #2ecc71;

}

a{

cursor:pointer

}

.active {

border-bottom:1px solid white

}

<div class="Wrapper">

  <div class="mainInner bg_white">




    <div class="linkWrappers">

      <header class="headerMenu">

        <div class="anchorLinks smothscrollclass">

          <ul>

            <li><a id='home-link' onclick="activateLink('home-link')">Home</a></li>

            <li><a id='about-link' onclick="activateLink('about-link','aboutus')" >About</a></li>

            <li><a id='service-link' onclick="activateLink('service-link','service')" >Service</a></li>

            <li><a id='gallery-link' onclick="activateLink('gallery-link','gallery')" >Gallery</a></li>

            <li><a id='contact-link' onclick="activateLink('contact-link','contactus')" >Contact</a></li>

          </ul>

        </div>

      </header>


    </div>


    <div class="WrapperInner ">

      <section class="aboutus" id="aboutus">

        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute

          irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


      </section>

      <section class="service" id="service">

        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute

          irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>



      </section>

      <section class="gallery" id="gallery">

        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute

          irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


      </section>

      <section class="contactus" id="contactus">

        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute

          irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>


      </section>

    </div>


  </div>

</div>

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


查看完整回答
反对 回复 2022-10-08
?
温温酱

TA贡献1752条经验 获得超4个赞

使用纯js,您需要使用document.body.scrollTop;来定义滚动了多少,然后从所有li-s中删除活动样式并添加到当前或仅手动为每个删除前一个,for(let i = 0;i<liClass.length;i++){liClass[i].classList.remove("active")}然后通过ID或唯一类添加到当前定位它,工作正常对我来说 jQuery 是一样的$("body").scrollTop()



查看完整回答
反对 回复 2022-10-08
?
缥缈止盈

TA贡献2041条经验 获得超4个赞

我升级了一点,现在一切都清晰了;)


对于滚动,我使用纯 html 只需将 ID 添加到要滚动并添加的元素<a href="#theIdOfElement">


你问的我用 jQuery 做的课程


第二次编辑:


let  x=0;

$(document).ready(()=>{

  $("a").click((e)=>{

    //Removes class active from all a-s and all divs

    $("a").removeClass("active");

    $("div").removeClass("active");

    //Adds only to clicked one

    $(e.target).addClass("active");

    

    //Adds class active to divs that contain the text on which you clicked

    $("div:contains("+ $(e.target).text() +")").addClass("active");

  });

$(document).scroll(()=>{

    $("p").text( $(document).scrollTop());

        if($(document).scrollTop() >= 970){

        //If you want to get style permenent remove line below

    $("div").removeClass("active");

    $("#contacts").addClass("active");

  }

      else if($(document).scrollTop() >= 508){

     //If you want to get style permenent remove line below

    $("div").removeClass("active");

    $("#about").addClass("active");

  }

  else if($(document).scrollTop() >= 8){

     //If you want to get style permenent remove line below

    $("div").removeClass("active");

    $("#home").addClass("active");

  }



  });

})

/*This is for smooth scrolling*/

html {

  scroll-behavior: smooth;

}

.big {

  height: 500px;

  width: 100%;

  border: solid black 1px;

}

.active {

color:red;

}

<div id="main">

<div style="position:fixed;display:flex;justify-content:flex-end;width:100%">

  <p id="demo">0</p>

<a href="#home">Home</a>

<a href="#about">About Us</a>

<a href="#contacts">Contacts</a>

</div>

<div class="big" id ="home">Home</div>

<div class="big" id ="about">About Us</div>

<div class="big" id ="contacts">Contacts</div>

</div>

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

 

查看完整回答
反对 回复 2022-10-08
  • 3 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号