简体   繁体   中英

If in viewport; change border color

I have different divs and a menuebar which constis out of LI-elements.

<ul>
    <li><a href="#first" id="nav1" title="Next Section">FIRST</a></li>
    <li><a href="#second" id="nav2" title="Next Section">SECOND</a></li>
    <li><a href="#third" id="nav3" title="Next Section">THIRD</a></li>
    <li><a href="#fourth" id="nav4" title="Next Section">FOURTH</a></li>
</ul>

The names of the div are #first to #fourth.

If one of the DIVs (or more) is/ are in the viewport I want to change the color of the bottom-border for the li-element which links to this DIV.

For example: If DIV #third is in viewport the third LI-element (#nav3) should change its bottom-border to green. If it leaves the viewport it should change to white again.

  • Just for the time the DIV is in the viewport. As soon it leaves the viewport I want to undo the color change.

I tried it with jQuery Viewport: http://www.appelsiini.net/projects/viewport

My problem is that I can't figure out how to use this selector - I know it's basic stuff but I really can't figure it out.

$("#third:in-viewport").each(function() {
    $("#nav1, #nav2, #nav4").animate({ borderBottomColor: '#fff' },800);
    $("#nav3").animate({ borderBottomColor: 'green' },800);
});

Would be awesome if somebody could help me with this. Thanks a lot!

I would add a class to your DIVs, something like:

<div id="first" class="item"> // Your code <div>
<div id="second" class="item"> // Your code <div>
<div id="third" class="item"> // Your code <div>
<div id="fourth" class="item"> // Your code <div>

And then something like this in jQuery, to highlight the links:

$(".item:in-viewport").each(function() {
     var item_id = $(this).attr("id");
     // In viewport
     $("a[href=#" + item_id +"]").animate({ borderBottomColor: 'green' },800);     
     // Not in viewport
     $("a").not("a[href=#" + item_id +"]").animate({ borderBottomColor: '#fff' },800);
});

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