简体   繁体   中英

Adding a css class on scroll via javascript

I have a navigation with an empty div in each anchor tag that I am styling on hover.

html

<li><a href="#events">SPECIAL EVENTS <div></div></a></li>

css

a:hover div, a:active div{
    color: $black;
    height: 1px;
    background-color: $black;
    width: 100%;
    margin-top: 5px;
}

I also have a active class that I am attaching on click with some js. This is currently working correctly.

var currentDiv;

function addSelected(){

if(currentDiv !== undefined){
    $(currentDiv).removeClass("active");    
}

currentDiv = $(this).find('div');
$(currentDiv).addClass("active");
}

$(".menu a").click(addSelected);

What I am trying to do is attached that same active class based on the user scroll. I get most of it working, but I can't seem to figure how how to attached the class to the div, and not the anchor itself. Here is the js I'm working with.

js

    // Cache selectors
var lastId,
topMenu = $("#desktop-nav"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
  var item = $($(this).attr("href"));
  if (item.length) { return item; }
});

// Bind to scroll
$(window).scroll(function(){
// Get container scroll position
var fromTop = $(this).scrollTop()+topMenuHeight;

// Get id of current scroll item
var cur = scrollItems.map(function(){
 if ($(this).offset().top < fromTop){
   return this;
 }  
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";

if (lastId !== id) {
    lastId = id;
    // Set/remove active class
    menuItems

    //.parent().removeClass("active")
    //.end().filter("[href='#"+id+"']").parent().addClass("active");

    .removeClass("active");
    end().filter($("[href='#"+id+"']")).find('div').addClass("active");

    console.log(id);
}                   
});

I think the part that I am trying to change is this

"[href='#"+id+"']").parent()

but everything I try is either not working or giving me errors.

EDIT

Here is the fiddle that I am trying to modify.

fiddle link

尝试将其更改为在点击处理程序中使用find():

"[href='#"+id+"']").find('div')

Use children() instead of parent() or find()

Example:

 if (lastId !== id) {
       lastId = id;
       // add/remove active class on div
       menuItems
         .children().removeClass("active")
         .end().filter("[href='#"+id+"']").children().addClass("active");
   } 

I assume you've tried...

"[href='#"+id+"']").parent().find('div')

and/or...

"[href='#"+id+"'].div"

...if so, are you able to add a class or id to the div and target it that way?

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