简体   繁体   中英

i am trying add css to all ' li ' element after scroll down but it apply only first li

After scrolling down, it's applying only the home button.

Here is my code.

<ul class="mainmenu nav sf-menu" style="float: right;">
  <li class="active" id="scrl-li">
    <a href="index.html"><span>Home</span></a>
   </li>
   <li  id="scrl-li">
     <a href="about.html" ><span>About Us</span></a>
   </li>
   <li id="scrl-li">  
     <a href="about.html" ><span>Services</span></a>
   </li>
 </ul>

JavaScript code:

$(document).ready(function() {
    var scrollTop = 0;
    $(window).scroll(function() {
        scrollTop = $(window).scrollTop();
        $('.counter').html(scrollTop);

        if (scrollTop >= 100) {
            $("#scrl-li").css("marginTop","-20px");
        } else if (scrollTop < 100) {
            $("#scrl-li").css("marginTop","0px");
        } 
    });
});

其他海报是正确的,每页应该只有一个 ID,但如果您无法使用 $("[id='scrl-li' ]") 来定位元素而不是 $("#scrl-li")。

Id's should be unique and not repeated across elements. Changing your id's to classes makes this code work:

Change the jquery id references as well as the html id references to classes

<li id="scrl-li">

to...

<li class="scrl-li">

and....

$("#scrl-li")

to...

$(".scrl-li")

jsfiddle: https://jsfiddle.net/xpvt214o/794901/

View the html code as you scroll and you will see the margin attributes appear and change accordingly.

You cannot have more ids in your html template. You can have only one id="scrl-li".

In you html template replace the id with class and in the jquery instead of calling $("#scrl-li"), you will have to use $(".scrl-li").

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM