简体   繁体   English

使用Javascript和CSS的MenuBar

[英]MenuBar using Javascript and css

Hi I am trying to make a horizontal menu bar using CSS and Javascript. 嗨,我正在尝试使用CSS和Javascript制作水平菜单栏。 When clicked, I want the menu item to background to turn black. 单击后,我希望菜单项变为背景变黑。 Here is a part of HTML code- 这是HTML代码的一部分-

<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- JavaScript部分

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/ 演示: http//jsfiddle.net/ag9L09sb/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM