I have a working hashtag link system and I basically want to style the <li> to tell a user what page they are on using background and color. When you click on another list item the jQuery will update the previous page <li> CSS back to normal state.

How can I achieve this?

jQuery code:

function Init(){
 ShowPage ('#body_home');
}

 function ShowPage(a){
  $(a).css("display","block");
 }

 $(document).ready(function(){
   $("a").click(function(e){
       if(window.location.href!= 'index.php'){
        window.location.href== 'index.php';
      }else{
        noop();
      }
      $(".page").fadeOut(1000).delay(1500);
      $("#" + $(this).data("page")).fadeIn(1000); e.preventDefault(); return       false;
   });
});

HTML code:

<ul class="navlist">
    <li><a href="index.php">Home</a></li>
    <li><a href="hello.php">Hello</a></li>
</ul>
有帮助吗?

解决方案

I've simplified this answer to target the specific behaviour I think you're looking for, but you should be able to implement it for your specific case.

I would create a class and name it .selected or .active, and assign the styling you want to it. For example:

.selected {
    background: #f4a;
    color: #fff;
}

When an item is clicked, use jQuery to add the class to that item, and remove the class from all other items. For simplicity, the following example assumes the styling will be applied to the anchor, rather than the list item:

$('a').click( function() {
    $('a').not(this).removeClass('selected');
    $(this).addClass('selected');
});

It would be slightly trickier to target the parent li, but the solution would be the same.

Here's a fiddle demonstrating this solution.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top