简体   繁体   中英

how to active a link using javascript

I have following links

   <ul class="dropdown dropdown-horizontal">
        <li><a href="#" class="dir" onClick="clickMe('Wall'); selectedTab('Wall');">Wall</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Introduction');">Introduction</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Activities');">Activities</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Reviews');">Reviews</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Recommendation');">Recommendation</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Photos');">Photos</a></li>
        <li><a href="#" class="dir" onClick="clickMe('Discussion');">Discussion</a></li>
    </ul>

and if I click on any link then it must be high lighted.

我认为您需要a:active CSS伪选择器。

You don't need javascript to do this. Some CSS rules are enough.

Depending on which behaviour you need you could use one or all of this HTML pseudo-selectors ( :link , :visited , :hover , :active ).

The link selector specifies the behavior of the link when It's not clicked nor activated for any reason, in other words in its normal state.

The :active pseudo-class adds a style to an element that is activated.

If you need to be more specific and for example want to highlight what you mouseover (in other word only when the link is under your mouse) put this in the head section of your HTML:

<style type="text/css" media="screen">
    a:hover { background: #fbdbe8; color: #F55B99;}
</style>

If you want to highlight what you already visited vs what not put this in the head section of your HTML:

<style type="text/css" media="screen">
    a:visited { background: #fbdbe8; color: #F55B99;}
</style>

Then every clicked link would be highlighted when you come back to the page.

You can, of course add the style rules I said in an external .css file instead of having them in the head.

Hmm:

<a href="#" id='photos'
onclick="var photos=document.getElementById('photos');photos.style.background='chartreuse';false;">
Photos</a>

The easiest way would be to use jquery

You would have somthing like:

$('.menuItem').click(function() {
    $('.current').removeClass("curret"); // To remove the highlight from the previous selection
    $(this).addClass("current") 
});

Then in your css you would declare current with the styles you want. One advantage of this vs the css pseudo selector is that you can do something like $(this).parent() to access the parent element of the link, in case your menu is a ul.

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