简体   繁体   中英

MenuBar using Javascript and css

Hi I am trying to make a horizontal menu bar using CSS and Javascript. When clicked, I want the menu item to background to turn black. Here is a part of HTML code-

<ul id="top_menu">
                    <li onclick="arrow(this)"><a href="#">item no 1</a></li>
                    <li onclick="arrow(this)"><a href="#">item no 2</a></li>
                    <li onclick="arrow(this)"><a href="#">item no 3</a></li>
                    <li onclick="arrow(this)"><a href="#">item no 4</a></li>
                    <li onclick="arrow(this)"><a href="#">item no 5</a></li>
</ul>

JavaScript part-

function arrow(x){
                x.style.background="#000000";
            }

Now when someone clicks on the menu, the background turns black.The problem is when any other item is selected(clicked) the previous selected item doesn't goes back to its original background color. How should I implement this feature? Thanks!

There are few ways... This one is easiest to me:

function arrow(x){


    var ul = document.getElementById('top_menu');

list=ul.getElementsByTagName("li");

    for(i=0;i<list.length;i++){

        if(list[i]!==x){        
list[i].style.background="#ffffff";  
        }
        else {
             list[i].style.background="#000000";
        }
    }



            }

Demo: http://jsfiddle.net/ag9L09sb/1/

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