简体   繁体   中英

Highlight current page navigation item

I have a floating page navigation list on my site. It has all the headers of the page, and the user can comfortably click the page navigation items to go to the correct anchor of the page. It also helps greatly in letting the visitor understand page structure, and to know where on the page he/she is.

Now, to help the user understand where on the page he/she is, I'd like for the correct item in the page navigation list to get highlighted (adding/removing CSS classes) depending on where the user is.

I hope I have explained myself well. How is this done? Thanks!

- EDIT -

Thanks Talgat for your answer. I now have this code:

<body ng-app="myApp">

This is my controller:

<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("validateCtrl", function($scope) {
    $scope.isActive = {};
    $scope.isActive = function (state) {
        return state === $state.current.name;
    };
});
</script>

This is a anchor link from the navigation list to one of the tours we offer called "Ancestral Adventure":

<a href="#ancestral-adventure" ng-class="{active: isActive('ancestral-adventure')}">Ancestral Adventure</a>

"ancestral-adventure" is the id of a header. Perhaps I should wrap the "Ancestral Adventure"-content in a div instead with this id, though? This is the header:

<h3 id="ancestral-adventure" name="ancestral-adventure">Ancestral Adventure</h3>

As your angular code mentioned name in $state.current.name , I added a name and ng-name with same value to the header as well, just to be safe.

With this code, the navigation list items are not updated - nothing happens. I have made sure the active class works for the list items, and that the AngularJS library is working. What might I be doing wrong? Thanks!

You can use $state service to check is current navigation item is active or not. Here some example to realize that. Add following code to your controller:

$scope.isActive = function (state) {
  return state === $state.current.name;
};

and add this in templete:

<ul class="nav">
  <li ng-class="{active: isActive('route-name')}">
  </li>
</ul>

The active: isActive('route-name') will assign active class to the li tag if current item is active, then you can highlight that item with css.

So from what i understand you want to create sth like bootstrap ScrollSpy It requires calculating vertical scroll position against header element positions. You can try and use one of scroll spy implementations for angular. Two first results from google:

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